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

posted @   炽橙子  阅读(2195)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
点击右上角即可分享
微信分享提示