在 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()
返回一个始终解决并且从不拒绝的承诺。我已经在 Chrome 46.0.2490.86 和 Firefox 42.0 上尝试过此操作。为什么会出现这种情况?我以为then()
and catch()
可以多次链接吗?
就像同步代码中一样:
try {
throw new Error();
} catch(e) {
console.log("Caught");
}
console.log("This still runs");
运行的代码after异常已被处理将运行 - 这是因为异常是一种错误恢复机制。通过添加该捕获,您表明该错误已被处理。在同步情况下,我们通过重新抛出来处理这个问题:
try {
throw new Error();
} catch(e) {
console.log("Caught");
throw e;
}
console.log("This will not run, still in error");
Promise 的工作原理类似:
Promise.reject(Error()).catch(e => {
console.log("This runs");
throw e;
}).catch(e => {
console.log("This runs too");
throw e;
});
作为提示 - 切勿拒绝非Error
因为你会丢失很多有用的东西,比如有意义的堆栈跟踪。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)