-
直接用
async/await
同步操作,就是for
循环里面必须等await返回后才会执行第二次循环。与then
不同的是,then()
只有包裹在里面的方法里面才是异步返回后执行的。所以for
循环外层的return
可能会在异步返回前执行了。async fn(arr){ let arrItem =[] for(let i=0;i<arr.length;i+=1){ const res = await request() arrItem.push(res.arrItem) } return arrItem } 复制代码
调用
fn()
的时候可能会返回一个promise
对象,所以还得:fn2(){ fn().then(res=>{ }) } 复制代码
-
for
循环里直接return
跳出执行方法函数如果你想在
for/map
循环里面直接return
方法函数的值,建议你还是别找了。因为我是实在找不到。for
本来就是一个方法,return
只能返回他所在域的方法。所以还是推荐使用上面的async/await
。如果是满足条件后退出循环并返回,你可以给个状态fn(arr){ let status =false let item =null arr.map(item=>{ if(item.id===0){ item = item status = true; return false; } }) if(status){ return item; }else{ return false; } } 复制代码
-
map
里使用async/await
,我的使用方式是这样的,测试return
还是在请求返回前执行了,不知为何,大神能给个解释吗?之后解决的话会更新fn(arr){ let arrItem =[] arr.map(async(item=>{ const res = await request() arrItem.push(res.arrItem) }) return arrItem } 复制代码
转载于:https://juejin.im/post/5cd3ca1a6fb9a031e975378e