JS promises catch
Oct 6, 2015
2 minutes read

If you are writing modern JavaScript then promises are a very useful thing to have in your tool belt. However there are some pitfalls.

I want to share one good tidbit of information that I took from reading this article, which I highly recommend reading through.

I will just jump right into it:

So when you use promises, to get the resolved value you use the then method which takes two functions as arguments. The first is for success, the second called on error. Like this:

doSomethingAsync().then(function (data) {
// success!!
}, function(e) {
// error :(
} )

But there is one problem here. If there is an error in the first function the second will not be called. Instead, it will be sucked into a black hole. It will only be called if there is an error caused inside the DoSomethingAsync function.

The solution to this is to use the \“catch\” method. This will be called for an error in the callback passed to then and the function that returned the promise.

It looks like this:

doSomethingAsync().then(function (data) {
  throw 'something went wrong!';
}).catch( function(e) {
	// error in the success handler! :( but at least we caught it now.
} )

So in short, don’t use two callbacks with .then or some errors will get swallowed.

I verified this in a few common environments:

chrome: swallows error. Does tell you about uncaught error in console.
node: latest: swallows error.
IO.js: swallows error.
firefox: swallows error.
safari: …. also swallows error.

here is a gist for you to run yourself


Back to posts