2 回答
TA贡献1802条经验 获得超10个赞
它返回 1,因为您的代码永远不会到达 catch 块。为了达到它,你必须拒绝你的承诺。甚至字面上的 ( Promise.reject()) 或抛出错误:
示例 1:一切正常,没有拒绝:
Promise
.resolve(1)
.then(x => {
console.log(x);
return x + 1;
})
.then(x => {
console.log(x);
return x + 1;
})
.then(x => {
console.log(x);
return x + 1;
})
.catch(e => {
console.log('an error!!'); // block not reached
});
示例 2:拒绝承诺跳转到下一个 catch 块:
Promise
.resolve(1)
.then(x => {
console.log(x);
return x + 1;
})
.then(x => {
console.log(x);
throw Error('ops');
return x + 1;
})
.then(x => { // block not reached
console.log(x);
return x + 1;
})
.catch(e => {
console.log('an error!!');
});
示例 3:在 catch 块之后它正常运行:
Promise
.resolve(1)
.then(x => {
console.log(x);
return x + 1;
})
.then(x => {
console.log(x);
throw Error('ops');
return x + 1;
})
.catch(e => {
console.log('an error!!');
return 10;
})
.then(x => {
console.log(x);
return x + 1;
});
TA贡献1851条经验 获得超5个赞
当 x resolves 时,它的值为 1 当您尝试捕获 x 时,它返回 x 并在自身上添加了 catch 处理程序,因此 p1 指的是 x 本身但具有附加的 catch 处理程序 现在因为从 x 继承的 p1 已经解析,链接任何 then方法将使用已解析的 x 参数运行,因此这种行为
添加回答
举报
