Member-only story
JavaScript Promise.safe()
Defining a sane method to ignore promise errors.
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.
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:
- Fetch the resource from the database
- If the resource exists, return it to the caller.
- Otherwise, do some work.
- Upsert the resource.
- Return the resource to the caller.