Member-only story

JavaScript Promise.safe()

Defining a sane method to ignore promise errors.

Lincoln W Daniel
ModernNerd Code
5 min readOct 3, 2024

--

After being an engineer for over a decade, I know how this article must begin; accordingly, I must say the following in order to not be hung by the opinion powers that be:

I know that it’s not “best practice” to define fields on JavaScript Object prototypes that you do not own.

With that out of the way, I finally decided to define a Promise.prototype.safe() method, alongside the native Promise.prototype.then() and Promise.prototype.catch() methods.

Image by Lincoln W Daniel

Why would you want to do this? Well, let me show you a common process I go through in my codebase that supports millions of visitors and customers each year across my multiple online properties, such as ManyStories.com and OurTransfers.com.

The goal of this example of the process is to get a resource from the database or create it, through a non-trivial process, which cannot be fulfilled via the database engine’s upsert mechanism.

The process:

  1. Fetch the resource from the database
  2. If the resource exists, return it to the caller.
  3. Otherwise, do some work.
  4. Upsert the resource.
  5. Return the resource to the caller.

--

--

ModernNerd Code
ModernNerd Code

Published in ModernNerd Code

Learn to Code Life. Subscribe to Video Tutorials on Youtube

Lincoln W Daniel
Lincoln W Daniel

Written by Lincoln W Daniel

Chief Bull @ BullAcademy.org ® Elevating writers @ ManyStories.com. Author @JavaForHumans Ex: Editor in Chief MarkGrowth (acq.), Engineer @Medium @GoPuff

Responses (6)