为什么我所有已解析的回调都正确执行,但仅 1 错误回调正在运行?
在此处的示例中,如果 longOperation(true)
我只收到一个错误,而当使用 false 运行时,我收到两条已解决的消息。据我了解,每个 .then
返回一个新的 Promise,该 Promise 处于第二个 .then
错误回调注册的错误状态
此示例是使用 Typescript 编写的!
function longOperation(error) {
return new Promise < any > ((resolve, reject) => {
if (error) {
reject("Error")
} else {
setTimeout(function() {
resolve(true)
}, 1000)
}
})
}
let op = longOperation(true);
op
.then(result => {
console.log("Resolved #1")
}, undefined)
.then(result => {
console.log("Resolved #2")
}, undefined)
.then(undefined, error => {
console.log("Error1")
})
.then(undefined, error => {
console.log("Error2")
})
最佳答案
第一个错误处理程序捕获错误,就像常规的 catch
block 一样。如果您希望链接的 Promise 被拒绝,则必须重新抛出错误:
Promise.reject().then(() => {
console.log(1);
}).then(() => {
console.log(2);
}).then(null, e => {
console.log(3);
throw e; // <= rethrow here
}).then(null, e => {
console.log(4);
});
关于Javascript Promise 链接多个错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42054698/