【问题标题】:promise with .catch() rejected but appears as fulfilled in Promise.allSetteled [duplicate].catch() 的承诺被拒绝,但在 Promise.allSettled 中显示为已履行 [重复]
【发布时间】:2020-07-30 06:00:47
【问题描述】:

这里是问题的简化版;

有一些承诺,很少有.then() 链,还有一个用于错误处理的.catch() 块; 每个承诺都可能解决或拒绝,因此我使用Promise.allSetted 根据数组中的顺序和状态来了解哪个承诺失败;当所有承诺都解决时它工作正常,但当一个承诺被拒绝时,它的状态将在Promise.allSetteld 中显示为“已完成”;如果我删除 .catch() 块,它将按预期工作,但我们需要保留 .catch() 块以登录到商店;那么为什么它的行为不符合预期呢?有什么方法可以让它在.catch() 块中显示“拒绝”状态?

let a = Promise.resolve("a: Promise.resolved").then(response => response).catch(err=>console.log(err));

let b = Promise.reject("b: Promise.rejected").then(response => response); // no error handling

let e = Promise.reject("e: Promise.rejected").then(response => response).catch(err=>console.log(err));

Promise.allSettled([a,b,e]).then( values => console.log(values) );

【问题讨论】:

  • “那么为什么它的行为不像预期的那样?”好吧,如果你没有重新抛出它是“预期的”没有错误。

标签: javascript promise


【解决方案1】:

您可以从catch 块中抛出错误,以便在catch 中不处理错误:

let a = Promise.resolve("a: Promise.resolved").then(response => response).catch(err => console.log(err));

let b = Promise.reject("b: Promise.rejected").then(response => response); // no error handling

let e = Promise.reject("e: Promise.rejected").then(response => response).catch(err => {
  console.log(err);
  throw err;
  //or Reject the Promise
  //return Promise.reject(err)
});

Promise.allSettled([a, b, e]).then(values => console.log(values));

这也在 Mozilla docs 中讨论过:

p.catch(onRejected);

onRejected

Promise 被拒绝时调用 Function

此函数有一个参数:reason 拒绝原因。承诺 如果onRejected 抛出错误,则catch() 返回的被拒绝或 返回一个本身被拒绝的Promise;否则,已解决

【讨论】:

    【解决方案2】:

    是的,现在我明白了,我们.catch() 它! 因此,通过使用.catch()(或在try{}catch(e){} 中捕获),我们告诉程序:“不要惊慌,一切都在控制之中”,“我会处理的”。现在说得通了。如果我们处理它而不抛出错误,听起来一切都很好;是的,为什么不呢?应该是fulfilled

    【讨论】:

      猜你喜欢
      • 2017-12-07
      • 2015-11-16
      • 2021-08-02
      • 1970-01-01
      • 2018-07-04
      • 2017-06-04
      • 2023-04-05
      • 2019-08-31
      • 1970-01-01
      相关资源
      最近更新 更多