js:使用Promise同步请求异步操作,即同时请求几个接口,等待全部接口请求完成再进行操作
使用`Promise.all().then()`
·
有些需求,需要同时请求多个接口,等待完多个接口都完成请求后,再进行下一步逻辑处理。这里就需要用到Promise.all()
。该方法用于将多个Promise实例,包装成一个新的Promise实例。
例如下面例子的代码:同时请求 getData1 和 getData2,等它们都完成请求后,执行 then() 或 error()。其中,api1 和 api2 是封装好的接口请求的方法。
Promise.all([
this.getData1(),
this.getData2()
]).then((result)=>{
console.log('result: >>', result)
}).catch((error) => {
console.log('error: >>', error)
})
async getData1() {
await api1()
},
async getData2() {
await api2()
}
关于更多的Promise.all的理解,可以查看此文章:promise.all的用法讲解。
更多推荐
已为社区贡献6条内容
所有评论(0)