mags mags - 2 years ago 89
Javascript Question

"throw new Error()" caught in catch block context

I've simplified the scenario in the code below because I don't have room here to explain my use case, but basically I'm throwing an error from the "catch" block of a promise. How can I get the error to get passed on from that catch block (in the example below I want the error to get reported from the outer "catch" block of the "try/catch" that I have wrapped my code with):

var pOuter = new Promise(function(resolve, reject){

var p = new Promise(function(resolve, reject) {
setTimeout(function() {
}, 1000);


p.then(function() {
//resolve outer promise
}).catch(function() {
//throw error should reject outer promise
reject(new Error('I want to get out of this catch block!'));

}).catch(function(err){console.log('I want to catch the error from the inner promise: ' + err.message)});

Answer Source

The catch handlers in a Promise are just as asynchronous as the promise itself, so you can't revert back to synchronous flow/exception control from them. The function you're passing into .catch may not be called until well after the try/catch surrounding it has exited.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download