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
对象,因此还得:promise
fn2(){
fn().then(res=>{
})
}
复制代码
for
循环里直接return
跳出执行方法函数若是你想在for/map
循环里面直接return
方法函数的值,建议你仍是别找了。由于我是实在找不到。for
原本就是一个方法,return
只能返回他所在域的方法。因此仍是推荐使用上面的async/await
。若是是知足条件后退出循环并返回,你能够给个状态bash
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
}
复制代码