如何使用 Promise-all--

Promise 在處理異步操作時很有用。

JavaScript 提供了一個輔助函數 Promise.all(promisesArrayOrIterable) 來同時並行處理多個 promise,並在單個聚合數組中獲取結果。讓我們看看它是如何工作的。

1. Promise.all()

Promise.all() 接受一組 promises(或通常是一個可迭代的)。該函數返回一個 promise:

const allPromise = Promise.all([promise1, promise2, ...]);

然後您可以使用 then-able 語法提取 Promise 解析的值:

allPromise.then(values => {
  values; // [valueOfPromise1, valueOfPromise2, ...]
}).catch(error => {
  error;  // rejectReason of any first rejected promise
});

或 async/await 語法:

try {
  const values = await allPromise;
  values; // [valueOfPromise1, valueOfPromise2, ...]
} catch (error) {
  error;  // rejectReason of any first rejected promise
}

2. 所有的 Promise fulfilled

爲了研究如何 Promise.all() 工作,我將使用 2 個助手 -resolveTimeout(value, delay) 和 rejectTimeout(reason, delay).

function resolveTimeout(value, delay) {
  return new Promise(
    resolve => setTimeout(() => resolve(value), delay)
  );
}

function rejectTimeout(reason, delay) {
  return new Promise(
    (r, reject) => setTimeout(() => reject(reason), delay)
  );
}

resolveTimeout(value, delay) 在經過 delay 時間後返回一個 value 的 Promise 。

另一方面,rejectTimeout(reason, delay) 在經過 delay 時間後返回 reject 的 Promise(通常是一個錯誤)。

const allPromise = Promise.all([
  resolveTimeout(['potatoes', 'tomatoes'], 1000),
  resolveTimeout(['oranges', 'apples'], 1000)
]);

// wait...
const lists = await allPromise;

// after 1 second
console.log(lists); 
// [['potatoes', 'tomatoes'], ['oranges', 'apples']]

promises 數組的順序直接影響結果的順序。

3. 一個 Promise rejects

const allPromise = Promise.all([
  resolveTimeout(['potatoes', 'tomatoes'], 1000),
  rejectTimeout(new Error('Out of fruits!'), 1000)
]);

try {
  // wait...
  const lists = await allPromise;
} catch (error) {
  // after 1 second
  console.log(error.message); // 'Out of fruits!'
}

這種行爲 Promise.all([...]) 被命名爲 fail-fast。如果 promises 數組中至少有一個 promise 拒絕,則 allPromise = Promise.all([...])rejects 返回的 promise 也會被拒絕。

4. 結論

Promise.all() 方法接收一個 promise 的 iterable 類型(注:Array,Map,Set 都屬於 ES6 的 iterable 類型)的輸入,並且只返回一個 Promise 實例, 那個輸入的所有 promise 的 resolve 回調的結果是一個數組。這個 Promise 的 resolve 回調執行是在所有輸入的 promise 的 resolve 回調都結束,或者輸入的 iterable 裏沒有 promise 了的時候。它的 reject 回調執行是,只要任何一個輸入的 promise 的 reject 回調執行或者輸入不合法的 promise 就會立即拋出錯誤,並且 reject 的是第一個拋出的錯誤信息。

本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源https://mp.weixin.qq.com/s/cpnHD0wRfVH__5LeVEvD2g