Safe Promises in Node.js


A micro-article about making Promises safe to use in Node.js.

Are Promises Unsafe?

Only if misunderstood. Misunderstanding Promises = death, destruction and despair for your application.

Luckily, there are solutions for that.

List of Entries

  1. Using Promise.all() & unbounded Promise scenarios
  2. Promises without .catch() handler
  3. Invisible Promise.race() rejections

Concerns & Solutions

1. Using Promise.all() & unbounded Promise scenarios

Impact: Event loop starvation, unnecessary memory usage, bottlenecked throughput.

Context: Read Promise.allpocalypse, an excellent article about the performance implications of Promise.all(), by Ali Yousuf.

Related npm package: promise-limit by GH/featurist

2. Promises without .catch() handler

Impact: File descriptor & memory leaks.

Context: Read “The Problem” by @matteocollina.

Solution:

  1. Always use make-promises-safe so uncaught exceptions become visible.
  2. Handle Promise exceptions appropriately.

Related npm package: make-promises-safe by @matteocollina

3. Invisible Promise.race() rejections

Impact: File descriptor & memory leaks (see: “Promises without .catch() handler”).

Context: @eDominykas on Promise.race().

Solution: Add .catch() handlers to all racing Promises.

Warning: make-promises-safe does not cover the Promise.race() case.

Reading Material