mags mags - 5 months ago 21
Javascript Question

"throw new Error()" caught in catch block context in mocha.js

******Edited from original

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 to my mocha test.



it('should fail as pending', function(done){
var p = new Promise(function(resolve, reject) {
setTimeout(function() {
reject();
}, 1000);

});

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



});




Answer

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.