为了账号安全,请及时绑定邮箱和手机立即绑定

为什么承诺捕获仍然获得解决价值

为什么承诺捕获仍然获得解决价值

缥缈止盈 2021-08-26 16:40:23
我试图理解为什么带有空参数的 promise catch 仍然得到解析值 1var x = Promise.resolve(1);var p1 = x.catch(null);p1.then((x) => {  console.log(x)}); // logs 1
查看完整描述

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;

});


查看完整回答
反对 回复 2021-08-26
?
江户川乱折腾

TA贡献1851条经验 获得超5个赞

当 x resolves 时,它的值为 1 当您尝试捕获 x 时,它返回 x 并在自身上添加了 catch 处理程序,因此 p1 指的是 x 本身但具有附加的 catch 处理程序 现在因为从 x 继承的 p1 已经解析,链接任何 then方法将使用已解析的 x 参数运行,因此这种行为


查看完整回答
反对 回复 2021-08-26
  • 2 回答
  • 0 关注
  • 198 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号