forEach、map、for..of、for..in、for循環實現異步變同步的問題


1.結論:forEach、map不支持異步變同步。

let arr=[1,2,3,4,5];
function asyncEvent(ele){
    return new Promise(resolve=>{
        setTimeout(e=>{
              console.log(e);
              resolve(e)
    },1000,ele);
  })
}

1.for...of

async function test(){
for(let i of arr){
await asyncEvent(i);
}
console.log("next");
}
test();

 

2.for()

async function test(){
for(let i=0;i<arr.length;i++){
await asyncEvent(arr[i]);
}
console.log("next");
}
test();

 

3.for...in

async function test(){
for(let i in arr){
await asyncEvent(arr[i]);
}
console.log("next");
}
test();

 

 

4、Promise.all()

用這個方法,需要將接下來進行的操作放在then中執行,Promise.all會將幾個異步操作並列執行,最終執行完成后的結果放在res中

async function test(){
Promise.all(arr.map( async ele=>{
return await asyncEvent(ele);
})).then(res=>{
console.log(res)
console.log("is start");
});
}
test();

 

 

 

 

 

轉:https://blog.csdn.net/weixin_42756432/article/details/103880033?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.edu_weight&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.edu_weight


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM