处理承诺中的错误 [英] Processing errors in promises
本文介绍了处理承诺中的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图弄清楚如何正确处理承诺链中的错误.几乎没有承诺,其中之一会引发错误.如果出现错误,我想终止链中的功能.
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.
我面临的问题是:
- 我们如何终止来自 catch 块的下一个调用?
- 如何保证 then().catch().then() 链的执行顺序?在这我观察到在执行两个 then() 函数后调用了 catch 块.
代码示例:
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");
});
}
推荐答案
你只是在链条的末端.如果有什么错误.它将忽略其他 then
并直接捕获.
You just catch at the end of the chain. If there's any error. It will ignore the other then
and go direct to catch.
function test() {
return new Promise(function(fulfill, reject) {
ask()
.then(reply())
.then(function(data) {
console.log("w3", "Finish test");
return fulfill(data); // <= Make sure to return here
// TODO finish data
})
.catch(err => console.log("w3", "Process error from reply: " + err))
});
}
确保返回 Promise 否则它不会捕获您的错误.
Make sure to return Promise or else it won't catch your error.
fulfill(data);
应该是 returnfulfill(data);
这篇关于处理承诺中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文