You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js中Promise.all与逐个async/await的性能对比疑问

为什么Promise.allSettled没有比逐个await更快?

我仍在学习理解Promise.all,因此编写了一个简单脚本,对比Promise.allSettled与逐个使用await调用函数(函数内部通过while循环实现计算逻辑)的性能差异。我原本认为Promise.all会因并行执行而快很多,但脚本运行结果却并非如此。请问这个脚本是否过于简单,我是否忽略了某些关键细节?

const p1 = async () => {
  let x = 0
  
  while(x < 100000000) {
    x++
  }
  return x
}

const p2 = async () => {
  let y = 100000000
  
  while(y > 0) {
    y--
  }
  return y
}

const p3 = async () => {
  let z = 0
  
  while(z < 200000000) {
    z = z + 2
  }
  return z
}

const run1 = async () => {
   console.time("Parallel")
   
   const [res1, res2, res3] = await Promise.allSettled([p1(), p2(), p3()])
   console.log(res1.value, res2.value, res3.value)
   
   console.timeEnd("Parallel")
}

const run2 = async () => {
   console.time("Sync")
   
   const res1 = await p1()
   const res2 = await p2()
   const res3 = await p3()
   console.log(res1, res2, res3)
   
   console.timeEnd("Sync")
}

run1()
// run2()

运行结果

运行结果


核心原因解析

  • JavaScript是单线程运行环境,你的p1/p2/p3函数里的while循环是同步阻塞的CPU密集型任务,这类任务会占用主线程直到执行完毕,根本无法并行。
  • 异步函数中如果没有真正的异步操作(比如await setTimeout、网络请求、文件IO等),调用函数时会直接同步执行完所有代码,再返回Promise。所以Promise.allSettled([p1(), p2(), p3()])本质上还是按顺序执行三个while循环,和逐个await的耗时几乎一致。

如何体现Promise并行优势?

要让Promise发挥并行作用,必须使用真正的异步IO任务——这类任务会把耗时操作交给浏览器/Node.js的底层线程处理,主线程可以空闲下来处理其他任务,从而实现并行。

修改后的示例:

const p1 = async () => {
  // 模拟异步网络请求
  await new Promise(resolve => setTimeout(resolve, 1000));
  return 100000000;
}

const p2 = async () => {
  await new Promise(resolve => setTimeout(resolve, 1000));
  return 0;
}

const p3 = async () => {
  await new Promise(resolve => setTimeout(resolve, 1000));
  return 200000000;
}

const run1 = async () => {
   console.time("Parallel")
   const [res1, res2, res3] = await Promise.allSettled([p1(), p2(), p3()])
   console.log(res1.value, res2.value, res3.value)
   console.timeEnd("Parallel") // 耗时约1秒
}

const run2 = async () => {
   console.time("Sync")
   const res1 = await p1()
   const res2 = await p2()
   const res3 = await p3()
   console.log(res1, res2, res3)
   console.timeEnd("Sync") // 耗时约3秒
}

run1()
// run2()

总结

  • Promise的“并行”仅适用于异步IO任务,无法加速同步CPU密集型任务
  • 你的脚本没有包含真正的异步操作,因此两种执行方式性能差异不大
  • JavaScript单线程特性决定了同步任务只能排队执行,若要处理CPU密集型任务,需借助Web Worker(浏览器)或Worker Threads(Node.js)实现真正的并行

内容的提问来源于stack exchange,提问作者Dally

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 08:43:14