在实际项目中,经常会遇到循环列表,根据id去掉接口获取数据,当列表中的每一项都获取完数据的时候再去执行其他操作,此时需要用到Promise.all来用于等待多个异步计算
let arr = [
{id:1,name:'111'},
{id:2,name:'222'},
{id:3,name:'333'},
]
a(){
return new Promise((resolve,reject)=>{
let arr2=[]
arr.forEach(v=>{
const p = new Promise((res,rej)=>{
api.get(v.id).then(api_res=>{ //调用接口
console.log("接口获取数据成功",api_res)
res() //单个接口执行完毕
})
})
arr2.push(p)
})
Promise.all(arr2).then((result) => {
console.log(result)
resolve() //所有接口都执行完毕
})
})
},
b(){
a().then(res=>{
console.log("所有接口都请求完了")
//在此处执行其他操作
})
}