Skip to content

Promise.all

一句话解释

Promise.all 接收 promise 可迭代对象,在全部完成时以结果数组解析,或在首次拒绝时拒绝。

用大白话说

Promise.all 并发运行多个 promise 并等待全部成功。它返回单个 promise,在所有输入 promise 完成后以结果数组(与输入同序)解析。若任一 promise 拒绝,Promise.all 立即以该原因拒绝(短路)。结果数组保持输入顺序,无论哪个 promise 先解析。这非常适合并行获取多个独立资源:const [user, posts] = await Promise.all([fetchUser(), fetchPosts()]) 同时运行两个请求而非顺序。若想容忍部分失败,改用 Promise.allSettled(它从不拒绝,给出每个 promise 的状态)。Promise.all 是"我需要这些全部成功"的首选组合器。

示例

javascript
async function loadDashboard(userId) {
  const [user, posts, friends] = await Promise.all([
    fetch(`/api/users/${userId}`).then(r => r.json()),
    fetch(`/api/posts?user=${userId}`).then(r => r.json()),
    fetch(`/api/friends/${userId}`).then(r => r.json()),
  ]);
  return { user, posts, friends }; // all three ran in parallel
}

// If any fetch fails, the whole Promise.all rejects.

三个 fetch 并发运行。Promise.all 等待全部并按序返回结果。任一拒绝即短路。

相关术语

相关资源

相关课程

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表