Error control flow in javascript promise chains (bluebird)

published Jun 18, 2016 01:00   by admin ( last modified Jun 18, 2016 01:01 )

You can catch an error, but what does that mean for the control flow?

Consider this test script:

const P = require('bluebird')
function bad(){
return sdfffsf // this will throw an error
}
P.resolve(8).then(x=>x).then(bad).catch(e=>console.log('We got an error' + e)).then(x=>console.log('We got here' + x))

That script will print "We got here". The chain was not terminated early due to the error, because we put an error handler in between the function that threw the error and the function that printed to the console.

However, this will not print "We got here" because the error handler is after the print statement.

const P = require('bluebird')
function bad(){
return sdfffsf
}
P.resolve(8).then(x=>x).then(bad).then(x=>console.log('We got here' + x)).catch(e=>console.log('We got an error' + e))

 

So in a nutshell, .catch allows you to skip from the point of error and resume execution in the pipeline at an arbitrary point down the line. Remember to rethrow the error unless you want the rest of the pipeline after the catch handler to get executed.