【发布时间】:2023-04-02 10:50:02
【问题描述】:
我有一个承诺链:
Promise
.then(function() {
if (some condition) {
Promise.reject("Request cancelled");
}
return doSomething1();
})
.then(function() {
if (some condition) {
Promise.reject("Request cancelled");
}
return doSomething2();
})
.then(function() {
if (some condition) {
Promise.reject("Request cancelled");
}
return doSomething3();
})
.catch(function(err) {
if (err == "Request cancelled") {
// err handling here
}
})
在每个 .then() 中,都有相同的代码检查是否破坏承诺链:
// repeated code
if (some condition) {
Promise.reject("Request cancelled");
}
我需要这样做,因为我想在发现错误后立即停止其余的异步调用,以便应用程序可以节省一些内存和时间。但它看起来真的很凌乱和多余。
所以我的问题是:有没有办法编写这段代码并避免重复代码?
谢谢!
【问题讨论】:
标签: promise coding-style code-cleanup