100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > forEach map for..of for..in for循环实现异步变同步的问题

forEach map for..of for..in for循环实现异步变同步的问题

时间:2020-10-29 06:29:52

相关推荐

forEach map for..of for..in for循环实现异步变同步的问题

一、背景

开发中经常遇到,遍历去查询服务获取数据,并且后边的代码需要借用上边查询到的数据,但是查询服务是一个异步操作,运用forEach或者map循环,在还没有查询到数据后,就执行了下一步操作,所以以下有几种方法可以实现异步变同步

二、问题

1、首先举个例子,执行test函数,要求先输出1、2、3、4、5,然后再输出“next”

let arr=[1,2,3,4,5];function asyncEvent(ele){setTimeout(e=>{console.log(e);},500,ele);}function test(){arr.map( ele=> asyncEvent(ele));console.log("next");}test();

2、从动画中可以看出,是先执行“next”,再执行数字,并且数字是同时展示出来的

三、解决方案

1、实现同步的方法

将要执行的异步方法封装成一个Promise返回,运用async/await方法,当异步函数里执行resolve时,await接收到成功的指示,然后进行下一步,实现结果如下

首先将异步函数用用Promise封装一下, 然后调用的时候用await去调用

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

a、for...of...

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

b、for ()循环

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

c、for...in...

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

d、while(){}

async function test(){let len=arr.length;while(len--){await asyncEvent(arr[len]);}console.log("next");}test();

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

2、不能实现同步的方法(以下方法实现不了,仅做错误实例)

a、forEach()

async function test(){arr.forEach(async ele=> await asyncEvent(ele));console.log("next");}test();

b、map()

async function test(){arr.map(async ele=> await asyncEvent(ele));console.log("next");}test();

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。