MDN’s new design is in Beta! A sneak peek: https://blog.mozilla.org/opendesign/mdns-new-design-beta/

Promise.all()

翻譯不完整。請協助 翻譯此英文文件

Promise.all() 方法會回傳一個 Promise 物件,此 promise 物件會於 iterable 參數中的所有 promise 都 resolved 時轉為 resolved 狀態,或是在其中的任一個 promise 變 reject 傳入失敗訊息時轉成 rejected 狀態。

語法

Promise.all(iterable);
iterable
An iterable object (such as an Array) of promises.

回傳值

A Promise that resolves when all of the promises in the given iterable have resolved, or rejects if any of the promises rejects.

描述

This method can be useful for aggregating the results of multiple promises.

Fulfillment:
If all of the passed-in promises fulfill, Promise.all is fulfilled with an array of the values from the passed-in promises, in the same order as defined in the iterable.
If an empty array is passed, then this method resolves immediately.

Rejection:
If any of the passed-in promises reject, Promise.all immediately rejects with the value of the promise that rejected, whether or not the other promises have resolved.

範例

Using Promise.all

Promise.all waits for all fulfillments (or the first rejection).

var p1 = Promise.resolve(3);
var p2 = 1337;
var p3 = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, 'foo');
}); 

Promise.all([p1, p2, p3]).then(values => { 
  console.log(values); // [3, 1337, "foo"] 
});

Promise.all fail-fast behaviour

Promise.all is immediately rejected if any of the elements are rejected. For example, if you pass in four promises that resolve after a timeout and one promise that rejects immediately, then Promise.all will reject immediately.

var p1 = new Promise((resolve, reject) => { 
  setTimeout(resolve, 1000, 'one'); 
}); 
var p2 = new Promise((resolve, reject) => { 
  setTimeout(resolve, 2000, 'two'); 
});
var p3 = new Promise((resolve, reject) => {
  setTimeout(resolve, 3000, 'three');
});
var p4 = new Promise((resolve, reject) => {
  setTimeout(resolve, 4000, 'four');
});
var p5 = new Promise((resolve, reject) => {
  reject('reject');
});

Promise.all([p1, p2, p3, p4, p5]).then(values => { 
  console.log(values);
}, reason => {
  console.log(reason)
});

//From console:
//"reject"

//You can also use .catch
Promise.all([p1, p2, p3, p4, p5]).then(values => { 
  console.log(values);
}).catch(reason => { 
  console.log(reason)
});

//From console: 
//"reject"

規範

Specification Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'Promise.all' in that specification.
Standard Initial definition in an ECMA standard.
ECMAScript Latest Draft (ECMA-262)
The definition of 'Promise.all' in that specification.
Draft  

覽瀏器相容性

Feature Chrome Edge Firefox Internet Explorer Opera Safari Servo
Basic Support32.0(Yes)29.0No support197.1No support
Feature Android Chrome for Android Edge Mobile Firefox for Android IE Mobile Opera Mobile Safari Mobile
Basic Support4.4.432.0(Yes)29No support(Yes)8.0

參見

文件標籤與貢獻者

 此頁面的貢獻者: jackblackevo
 最近更新: jackblackevo,