不使用then()函数处理Promise.all()拒绝

根据我的理解,如果所有的诺言都得到了解决,Promise.all([promises])将返回一个已解决值的数组。另外,根据Promise.all() fail-fast behavior,如果任何承诺被拒绝,Promise.all()也将被拒绝。

const result = await Promise.all([...promises]);

那么如果拒绝任何承诺,result变量的值是多少?它是否返回带有拒绝值的数组?如何确保不使用then()回调就能解决所有的诺言?我在整个项目中都使用async-await模式,但不想使用回调/承诺。

hellobaby12321 回答:不使用then()函数处理Promise.all()拒绝

如果数组中的任何promise抛出,则未定义结果变量,您将进入catch块。

(async () => {
  let result;
  try {
    const promise1 = Promise.resolve(1);
    const promise2 = Promise.resolve(2);
    const promise3 = Promise.reject();
    result = await Promise.all([promise1,promise2,promise3]);
  }
  catch(err) {
   console.log("a promise has thrown");
  }
  finally {
    console.log(result);
  }
})()

本文链接:https://www.f2er.com/3153118.html

大家都在问