[英]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 resolves时,它的值为1当您尝试捕获x时,它返回x并添加了catch处理程序,因此p1引用x本身,但具有其他catch处理程序现在,因为从x继承的p1已被解析,因此链接任何方法将使用已解析的x参数运行,因此此行为
它返回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; });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.