我仍然在尝试理解Promise. all,所以写了一个简单的脚本来查看Promise. all与使用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()
- 结果**
1条答案
按热度按时间v09wglhw1#
不要忘记js是单线程的,所以主线程上的计算是以牺牲其他函数为代价的,所以例如p1和p2“并行”运行,但在同一个事件循环上。
正如你在第二个例子中看到的,对于非计算密集型任务,Promise.all需要的时间与它最长的promise一样长,而链接则需要所有promise的总和。