Ste*_*eve 13 node.js promise bluebird
我被引导相信Promise.all会并行执行你传递它的所有函数,而不关心返回的promises完成的顺序.
但是当我写这个测试代码时:
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!")
})
Run Code Online (Sandbox Code Playgroud)
我得到的结果就是这个
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!
Run Code Online (Sandbox Code Playgroud)
但如果它们并行运行我不会期望它们同时执行并给我这样的结果吗?
Done Err!
Done True!
Done Err!
Done True!
Done Err!
Done True!
Done Err!
Done True!
Etc. Etc.?
Run Code Online (Sandbox Code Playgroud)
或者我错过了我正在做的事情?
Joh*_*erz 12
这是因为你的Promise是阻塞和同步的!尝试使用超时而不是同步循环:
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!")
})
Run Code Online (Sandbox Code Playgroud)
我建议像这样使用它:
const [
res1,
res2
] = await Promise.all([
asyncCall1(),
asyncCall1(),
]);
Run Code Online (Sandbox Code Playgroud)