JS中的Promise.all()和Promise.allSettled()之间的区别? [英] Differences between Promise.all() and Promise.allSettled() in JS?

查看:450
本文介绍了JS中的Promise.all()和Promise.allSettled()之间的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 Promise 上的 MDN 手册,发现这两种方法似乎与我相似:

I was reading the MDN's manual on Promise, and I found these two methods which seem similar to me:

  • Promise.allSettled(iterable);
  • Promise.all(iterable);

两者都需要一个 iterable 并返回一个包含已完成的 Promise s的数组。

Both of them take an iterable and return an array containing the fulfilled Promises.

那么,什么

推荐答案

Promise.all 会被拒绝,因为数组中的一个拒绝。

Promise.all will reject as soon as one of the Promises in the array rejects.

Promise.allSettled 将永不拒绝-数组中的所有 all 承诺被拒绝或解决后,它就会解决。

Promise.allSettled will never reject - it will resolve once all Promises in the array have either rejected or resolved.

Thei r解析值也不同。 Promise.all 将解析为Promises解析为的每个值的数组-例如 [Promise.resolve(1),Promise.resolve (2)] 将变成 [1、2] Promise.allSettled 会给您 [{status:'fulfilled',value:1},{status:'fulfilled',value:2} ]

Their resolve values are different as well. Promise.all will resolve to an array of each of the values that the Promises resolve to - eg [Promise.resolve(1), Promise.resolve(2)] will turn into [1, 2]. Promise.allSettled will instead give you [{ status : 'fulfilled', value: 1 }, { status : 'fulfilled', value: 2 }].

Promise.all([Promise.resolve(1), Promise.resolve(2)])
  .then(console.log);
Promise.allSettled([Promise.resolve(1), Promise.resolve(2)])
  .then(console.log);

如果承诺之一拒绝,则 Promise.all 将拒绝并带有拒绝值,但是 Promise.allSettled 将使用对象进行解析{状态:已拒绝,原因:<错误> } 在数组中的该位置。

If one of the Promises rejects, the Promise.all will reject with a value of the rejection, but Promise.allSettled will resolve with an object of { status: 'rejected', reason: <error> } at that place in the array.

Promise.all([Promise.reject(1), Promise.resolve(2)])
  .catch((err) => {
    console.log('err', err);
  });
Promise.allSettled([Promise.reject(1), Promise.resolve(2)])
  .then(console.log);

这篇关于JS中的Promise.all()和Promise.allSettled()之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆