Promise.all 的并行操作? [英] Parallel operations with Promise.all?

查看:22
本文介绍了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天全站免登陆