I try to figure out how to proper handle errors in promise chain. There are few promises and one of them throws error. In case of error I would like to terminate function in chain.
The issues I faced with are:
- How can we terminate next call from catch block?
- How to guarantee execution order then().catch().then() chain? At this moment I observe catch block is called after execution of both then() functions.
Code sample:
function run() {
test().then(function(data) {
console.log("w3", "Print data: " + data);
});
}
function test() {
return new Promise(function(fulfill, reject) {
ask()
.catch(err => console.log("w3", "Process error from ask: " + err))
.then(reply())
.catch(err => console.log("w3", "Process error from reply: " + err))
.then(function(data) {
console.log("w3", "Finish test");
fulfill(data);
// TODO finish data
})
});
}
function ask() {
return new Promise(function(fulfill, reject) {
console.log("w3", "ask");
// fulfill("Hello");
reject("Cancel Hello");
});
}
function reply() {
return new Promise(function(fulfill, reject) {
console.log("w3", "reply");
fulfill("World!");
// reject("Cancel World");
});
}