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