如何使用 async/await 实现 Promise.all 的效果?

详细介绍了如何利用 async/await 实现 Promise.all 的并发效果,并比较了不同实现方法的优缺点。

异步编程 中等 Promise async await

使用 async/await 实现 Promise.all 的核心方法是直接对 Promise.all() 的结果使用 await 等待并行执行的结果数组,并通过 try/catch 处理错误。具体步骤如下:

  1. 基本实现方式
    async 函数内部调用 Promise.all() 封装多个异步操作,并用 await 等待结果返回:
    async function getResults() {
      try {
        const [result1, result2] = await Promise.all([
          fetchData(url1), 
          fetchData(url2)
        ]);
        console.log(result1, result2); // 输出并行结果数组
      } catch (error) {
        console.error("请求失败:", error); // 捕获任意一个失败的Promise
      }
    }
    getResults();
    
  2. 与原Promise.all的等效性
    • 并发执行:所有参数中的异步操作会同时启动,相当于原生 Promise.all 的并发机制(非顺序执行)。
    • 错误同步:任一异步操作失败时,立即触发 catch 块并返回首个错误。
  3. 对比传统await的缺陷
    避免如下串行写法——会丧失并发性能优势:
    // ❌ 错误示例(串行执行)
    const data1 = await fetchData(url1); // 先等待完成
    const data2 = await fetchData(url2); // 再开始执行
    
  4. 动态参数的处理
    若需处理异步函数数组,可将数组直接传入 Promise.all
    const requests = [taskA(), taskB(), taskC()];
    const results = await Promise.all(requests);
    
  5. 注意事项
    • 返回值类型await Promise.all() 返回结果始终是一个数组,需通过解构或索引获取结果。
    • 绑定作用域:确保 awaitasync 函数内部调用,否则会触发语法错误。