Let's say I have a conditional statement after which a promise is created. I want to create a shared .catch()
function that will be called every time any of my promises fail. However if I attach catch statements later - they are treated differently, why?
var p1;
var condition = true;
if (condition) {
p1 = new Promise(function(resolve, reject) {
setTimeout(function() { reject('BREXIT!'); }, 1000);
});
} else {
p1 = new Promise(function(resolve, reject) {
setTimeout(function() { resolve('REMAIN!'); }, 1000);
});
}
p1.catch(function(e) { console.error("1 I CATCH", e); } );
p1.catch(function(e) { console.error("2 I CATCH", e); } );
p1.then(function(e) { console.log("ALL DONE"); } );
// Actual output:
//
// 1 I CATCH BREXIT!
// 2 I CATCH BREXIT!
// Uncaught (in promise) BREXIT!
//
//==============================
// Expected output:
//
// 1 I CATCH BREXIT!
// ALL DONE
You can play with this code here: http://jsbin.com/lopuyid/edit?js,console
I do understand that I can solve this problem by moving the whole promise creation to separate function, and chaining everything. My question is why .catch()
statements don't actually catch anything and are executed all, instead of one? Isn't chaining things A.f1().f2()
the same as doing A.f1(); A.f2()
?
Update
If someone will come to this page through web search, read the great links under this post. To quickly fix the problem, without too much code change, you should update the very same promise after each catch and then:
p1 = p1.catch(function(e) { console.error("1 I CATCH", e); } );
p1 = p1.catch(function(e) { console.error("2 I CATCH", e); } );
p1 = p1.then(function(e) { console.log("ALL DONE"); } );