Promise.allSettled()
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2020.
Promise.allSettled()
静态方法采用可迭代的 Promise 作为输入并返回单个 Promise
。当所有输入的承诺都解决时(包括传递空的可迭代对象时),返回的承诺就会履行,并带有描述每个承诺结果的对象数组。
¥The Promise.allSettled()
static method takes an iterable of promises as input and returns a single Promise
. This returned promise fulfills when all of the input's promises settle (including when an empty iterable is passed), with an array of objects that describe the outcome of each promise.
Try it
语法
参数
返回值
¥Return value
Promise
是:
¥A Promise
that is:
- 已经满足了,如果传过来的
iterable
是空的。 - 当给定
iterable
中的所有承诺都已解决(履行或拒绝)时,异步履行。履行值是一组对象,每个对象都按照传递的承诺顺序描述iterable
中一个承诺的结果,无论完成顺序如何。每个结果对象都具有以下属性:status
-
一个字符串,
"fulfilled"
或"rejected"
,指示 Promise 的最终状态。 value
-
仅当
status
为"fulfilled"
时才出现。兑现承诺的价值。 reason
-
仅当
status
为"rejected"
时才出现。承诺被拒绝的原因。
iterable
非空但不包含待处理的 Promise,则返回的 Promise 仍会异步(而不是同步)实现。
描述
¥Description
Promise.allSettled()
方法是 承诺并发 方法之一。当你有多个不依赖于彼此才能成功完成的异步任务,或者你总是想知道每个 Promise 的结果时,通常会使用 Promise.allSettled()
。
¥The Promise.allSettled()
method is one of the promise concurrency methods. Promise.allSettled()
is typically used when you have multiple asynchronous tasks that are not dependent on one another to complete successfully, or you'd always like to know the result of each promise.
相比之下,如果任务相互依赖,或者如果你想在其中任何一个拒绝时立即拒绝,则 Promise.all()
返回的 Promise 可能更合适。
¥In comparison, the Promise returned by Promise.all()
may be more appropriate if the tasks are dependent on each other, or if you'd like to immediately reject upon any of them rejecting.
示例
使用 Promise.allSettled()
¥Using Promise.allSettled()
Promise.allSettled([
Promise.resolve(33),
new Promise((resolve) => setTimeout(() => resolve(66), 0)),
99,
Promise.reject(new Error("an error")),
]).then((values) => console.log(values));
// [
// { status: 'fulfilled', value: 33 },
// { status: 'fulfilled', value: 66 },
// { status: 'fulfilled', value: 99 },
// { status: 'rejected', reason: Error: an error }
// ]
规范
Specification |
---|
ECMAScript Language Specification # sec-promise.allsettled |
浏览器兼容性
BCD tables only load in the browser