我认为Promise.all会并行执行传递给它的所有函数,并且不关心返回的promise完成的顺序。
但是当我编写下面的测试代码时:
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!
但是如果它们并行运行,我不会期望它们同时执行并给出这样的结果吗?
Done Err!
Done True!
Done Err!
Done True!
Done Err!
Done True!
Done Err!
Done True!
Etc. Etc.?
或者我在做的方式上漏掉了什么吗?
Promise.all
无关。当你创建一个承诺时,传递的函数会立即评估,所以在调用Promise2
或Promise.all
之前,Promise1
的主体已经运行了。Javascript不是多线程的,所以你的for
循环永远不会像那样重叠。 - SimpleJPromise.all
如何工作的例子。承诺按照它们创建的顺序开始,但并行运行。 - SimpleJ