JavaScript Promises

I read Best Practices for Using Promises in JS. Here are some concise notes expanding on this topic.

  • Let’s use bluebird as Promise implementation for node
  • Use .then().catch() instead of .then(successCb, failCb)
1
2
3
4
5
6
7
8
9
10
11
12
const promise = (shouldResolve) => new Promise((resolve, reject) => {
if (shouldResolve) {
resolve();
} else {
reject();
}});
promise(arg)
.then(() => { /* success */ })
.catch(ExceptionToCatch, OtherExceptionToCatch, (err) => { /* error */})
.catch(StrangeExceptionToCatch, (err) => { /* error */})
.catch((err) => { /* error */}); // default

To define an exception to catch:

1
2
3
4
5
6
7
function MyCustomError() {}
MyCustomError.prototype = Object.create(Error.prototype);
promise(arg)
.then(() => { throw new MyCustomError() })
.catch(MyCustomError, (err) => {})
.catch((err) => {});
  • Promise.all([promiseA(a), promiseB(b)]) runs two async functions in parallel, but .then(() => {}) callback has no data result argument
  • Use .spread instead of .then to get this data: .spread((dataA, dataB) => {})
  • To limit concurrency, Promise.map([lotsOfStuff], promise, { concurrency: 3 }).then(() => {})
  • See also .reduce and .filter
  • You can “pipe” your .then functions. If you do this, you should probably avoid using anonymous functions and enjoy more reusability, modularity, testability, readability
1
2
3
4
readFile(data)
.then(JSON.parse)
.then(treatStuff)
.catch(handleError)
  • Don’t abuse this thing. It’s nice to read, but it breaks the event loop and could introduce race conditions
  • A better approach is to pipe inside the .then:
1
2
3
readFile(data)
.then(pipe(JSON.parse, treatStuff))
.catch(handleError)

Further reading: