for 循环里面有异步,如何实现同步操作

143 阅读1分钟

async function getMoney(){ var money=[100,200,300] 
for( let i=0; i<money.length; i++){ 
await compute.exec().then(()=>{ console.log(money[i]) //alert(i) }
)

# [forEach、map、for..offor..infor循环实现异步变同步的问题](https://www.cnblogs.com/ygyy/p/13299424.html)

1.结论:forEach、map不支持异步变同步。

[![复制代码](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/f30e6418d05f41e0b222d23fcd5b3426~tplv-k3u1fbpfcp-jj-mark:0:0:0:0:q75.image#?w=20&h=20&s=263&e=gif&b=c5d9e8)](<> "复制代码")

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();


4Promise.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();

参考文档 参考1

通常我使用的是第2/3 的方式,这个已经在项目中实现过了。验证没有问题