小编Rap*_*ida的帖子

Promise.all 是否并行运行承诺?

我看到很多人说 Promise.all 无法实现并行性,因为 node/javascript 运行在单线程环境上。然而,例如,如果我将 5 个 Promise 包装在 Promise.all 中,其中每个 Promise 在 3 秒后解析(一个简单的 setTimeout Promise),那么为什么 Promise.all 在 3 秒内解析所有它们而不是大约 15 秒(每次 5 x 3 秒)?

请参阅下面的示例:

function await3seconds () { 
    return new Promise(function(res) {
        setTimeout(() => res(), 3000)
    })
}

console.time("Promise.all finished in::")

Promise.all([await3seconds(), await3seconds(), await3seconds(), await3seconds(), await3seconds()])
    .then(() => {
        console.timeEnd("Promise.all finished in::")
})
Run Code Online (Sandbox Code Playgroud)

它记录:

Promise.all finished in::: 3.016s
Run Code Online (Sandbox Code Playgroud)

如果没有并行性,这种行为怎么可能?并发执行也无法在 3 秒内处理所有这些 Promise。

javascript parallel-processing node.js promise

2
推荐指数
1
解决办法
4519
查看次数