我想知道两个代码块是否基本相等:
const executePromises = function(listOfProviders){
let p = Promise.resolve(null);
for(let i = 0; i < listOfProviders.length; i++){
p = p.then(v => listOfProviders[i]());
}
return p;
};
我相信以上内容基本上等同于:
const executePromises = async function(listOfProviders) {
for(let i = 0; i < listOfProviders.length; i++){
await listOfProviders[i]();
}
};
有人看到差异吗?
答案 0 :(得分:2)
否。它们不一样。即使您按照某人在评论中指出的那样兑现了诺言。
差异:
async await
与for-loop
一起使用时,应该记住,只有在当前迭代中已解决了等待的诺言时,for循环才会进入下一个迭代。.then
中使用for-loop
时,for-loop
在等待下一次迭代之前不会等待promise分解。我已经对您的代码进行了调整以证明这一点。观察每个代码段中的不同时间点正在调用 Line A 。
在Async await
代码内的 for-loop
:
function createPromiseWhichResolveAfterOneSec(i) {
return new Promise((resolve, reject)=>{
setTimeout(()=>{
console.log("About to resolve promise with value:",i);//Line A
resolve(i);
},1000)
})
}
const executePromises = async function(listOfProviders) {
let p;
let i;
for(i = 0; i < listOfProviders.length; i++){
console.log("before", i);
p = await createPromiseWhichResolveAfterOneSec(i);
console.log("after", i);
}
console.log(i);
return p;
};
let listOfProviders = [1,2,3,4,5];
let promise = executePromises(listOfProviders);
promise.then(value => console.log("this is the final value of promise chain:",value)).catch(()=>{});
在then
中有for-loop
:
function createPromiseWhichResolveAfterOneSec(i) {
return new Promise((resolve, reject)=>{
setTimeout(()=>{
console.log("About to resolve promise with value:",i);//Line A
resolve(i);
},1000)
})
}
const executePromises = function(listOfProviders){
let p = Promise.resolve(null);
for(let i = 0; i < listOfProviders.length; i++){
console.log("before", i);
p = p.then(v => createPromiseWhichResolveAfterOneSec(i));
console.log("after", i);
}
return p;
};
let listOfProviders = [1,2,3,4,5];
let promise = executePromises(listOfProviders);
promise.then(value => console.log("this is the final value of promise chain:",value)).catch(()=>{});