在 Chrome 或 Firefox 的控制台选项卡上尝试这段代码
var p = new Promise(function(resolve, reject) {
setTimeout(function() {
reject(10);
}, 1000)
})
p.then(function(res) { console.log(1, 'succ', res) })
.catch(function(res) { console.log(1, 'err', res) })
.then(function(res) { console.log(2, 'succ', res) })
.catch(function(res) { console.log(2, 'err', res) })
结果会是
1 "err" 10
2 "res" undefined
我已经尝试了很多其他示例,但似乎第一个 then()
返回一个始终解决且从不拒绝的 promise 。我已经在 Chrome 46.0.2490.86 和 Firefox 42.0 上试过了。为什么会这样?我认为 then()
和 catch()
可以链接多次?
最佳答案
就像在同步代码中一样:
try {
throw new Error();
} catch(e) {
console.log("Caught");
}
console.log("This still runs");
异常处理之后运行的代码将运行 - 这是因为异常是一种错误恢复机制。通过添加该 catch,您表示错误已得到处理。在同步情况下,我们通过重新抛出来处理这个问题:
try {
throw new Error();
} catch(e) {
console.log("Caught");
throw e;
}
console.log("This will not run, still in error");
Promises 的工作方式类似:
Promise.reject(Error()).catch(e => {
console.log("This runs");
throw e;
}).catch(e => {
console.log("This runs too");
throw e;
});
作为提示 - 永远不要拒绝非错误
,因为你会丢失很多有用的东西,比如有意义的堆栈跟踪。
关于javascript - 'catch' 在原生 Promise 链中是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34222818/