Using promise.then(callback, callback) misses errors

One traditional example of using promises is

1 promise.then(callback, callback);

There exists one important caveat in this approach. Can you spot it?

Exception in success handler goes unnoticed

If the success handler throws exception, then it will not be caught and handled in the rejection handler as one would think.

An improved version would be to separate the error handler as its own step. Then chain that only after the success handler. This way exception in the success handler will be propagated to the correct place.

1 promise
2     .then(callback)
3     .catch(callback);

A real world example

This becomes important in longer promise chains. For example if renderResultPage throws an error, it will not end up in handleError as you might expect:

1 fetchUrl()
2     .then(parseValues)
3     .then(loadPreviousValuesFromDb)
4     .then(calculateTodaysQuote)
5     .then(writeBackToDb)
6     .then(renderResultPage, handleError)

it's better to use catch() to avoid this

1     ...
2     .then(writeBackToDb)
3     .then(renderResultPage)
4     .catch(handleError)

and catch all errors.

Test case

Mocha test case

Mocha

Test case available at

https://github.com/bytearcher/using-promise-then-callback-callback-misses-errors

Node doesn't wait for your database call to finish?

Node doesn't wait for your database call to finish?

Learn how asynchronous calls work and make your app run as you intended. Get short email course on asynchronicity and two chapters from Finish Your Node App.

Get Two Book Chapters