为什么 promise catch 仍然得到解决的价值
Why promise catch is still getting resolved value
我想了解为什么带有空参数的 promise catch 仍然得到解析值 1
var x = Promise.resolve(1);
var p1 = x.catch(null);
p1.then((x) => {
console.log(x)
}); // logs 1
当 x resolve 时,它的值为 1
当您尝试捕获 x 时,它 returns x 自身添加了捕获处理程序,因此 p1 指的是 x 本身,但带有额外的捕获处理程序
现在,由于从 x 继承的 p1 已经解析,链接任何 then 方法将 运行 与解析的 x 参数,因此这种行为
它 returns 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;
});
我想了解为什么带有空参数的 promise catch 仍然得到解析值 1
var x = Promise.resolve(1);
var p1 = x.catch(null);
p1.then((x) => {
console.log(x)
}); // logs 1
当 x resolve 时,它的值为 1 当您尝试捕获 x 时,它 returns x 自身添加了捕获处理程序,因此 p1 指的是 x 本身,但带有额外的捕获处理程序 现在,由于从 x 继承的 p1 已经解析,链接任何 then 方法将 运行 与解析的 x 参数,因此这种行为
它 returns 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;
});