有些需求,需要同时请求多个接口,等待完多个接口都完成请求后,再进行下一步逻辑处理。这里就需要用到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的用法讲解。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐