与Promise.all并行运行? [英] Parallel operations with Promise.all?

查看:134
本文介绍了与Promise.all并行运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被认为是Promise.all并行执行您传递给它的所有函数,并且不在乎返回的Promise的顺序.

I'm led to believe that Promise.all executes all the functions you pass it in parallel and doesn't care what order the returned promises finish.

但是当我编写此测试代码时:

But when I write this test code:

function Promise1(){
    return new Promise(function(resolve, reject){
        for(let i = 0; i < 10; i++){
            console.log("Done Err!");
        }
        resolve(true)
    })
}

function Promise2(){
    return new Promise(function(resolve, reject){
        for(let i = 0; i < 10; i++){
            console.log("Done True!");
        }
        resolve(true)
    })
}

Promise.all([ 
    Promise1(),
    Promise2()
])
.then(function(){
    console.log("All Done!")
})

我得到的结果是这个

Done Err!
Done Err!
Done Err!
Done Err!
Done Err!
Done Err!
Done Err!
Done Err!
Done Err!
Done Err!
Done True!
Done True!
Done True!
Done True!
Done True!
Done True!
Done True!
Done True!
Done True!
Done True!
Done!

但是,如果它们并行运行,难道我不希望它们同时执行并给我这样的结果吗?

But if they're running in parallel wouldn't I expect them to be executing at the same time and give me a result like this?

Done Err!
Done True!
Done Err!
Done True!
Done Err!
Done True!
Done Err!
Done True!
Etc. Etc.?

还是我在做某事时错过了什么?

Or am I missing something in the way I'm doing it?

推荐答案

这是因为您的Promise处于阻塞和同步状态!试试超时而不是同步循环:

It's because your Promises are blocking and synchronous! Try something with a timeout instead of a synchronous loop:

function randomResolve(name) {
  return new Promise(resolve => setTimeout(() => {
    console.log(name);
    resolve();
  }, 100 * Math.random()));
}

Promise.all([ 
    randomResolve(1),
    randomResolve(2),
    randomResolve(3),
    randomResolve(4),
])
.then(function(){
    console.log("All Done!")
})

这篇关于与Promise.all并行运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆