- 本文介绍一下Promise.all() 的常用场景
Promise 有好几个api, 这篇文章主要是讲 .all的常用场景
// api 方法一
getMethodsFirst(){
return new Promise((resolve, inject)=>{
// 调用一个后端接口,此处是调用已经封装好了的axios,所以大家可以根据自己项目中的接口方法灵活访问
getMethodsFirstApi().then((res:any)=>{
resolve(res) // 返回获取到的正确的数据
},(req:any)=>{
inject(req) //返回失败信息
})
})
}
// api 方法二
getMethodsSecond(){
return new Promise((resolve, inject)=>{
// 方法二的后端api调用接口
getMethodsSecondApi().then((res:any)=>{
resolve(res) // 返回获取到的正确的数据
},(req:any)=>{
inject(req) //返回失败信息
})
})
}
init(){
// 需要等到getMethodsFirst方法和getMethodsSecond方法都返回数据后再执行
Promise.all([this.getMethodsFirst(), this.getMethodsSecond()]).then((res:any)=>{
// res 接收的是一个数组,.all()方法中请求几个方法,数组的值就有几个
// res[0] 是this.getMethodsFirst()的返回成功的值 , res[1] 是this.getMethodsSecond()的返回成功的值
// 接收到返回值之后,就可以做自己想要做的事情了
})
}