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

原文地址:https://www.cnblogs.com/ygyy/p/13299424.html