关于javascript:并行请求多个异步接口

当关上页面须要很多初始信息时,需于调用好几个接口,如果采纳异步嵌套形式调研会重大缩短页面的关上工夫。页面关上的工夫是所有接口打开工夫的和。

所以须要并行申请全副接口,而后只须要期待最慢的接口返回。那么页面关上的工夫就是最慢的接口返回数据的工夫。

计划1:
先同时申请全副接口,而后开始 await。

const userInfoFc = this.getUser();
const authInfoFc = this.getAuth();
const orgInfoFc = this.getOrgTree();

// await命令前面是一个 Promise 对象

const userInfo = await userInfoFc;
const authInfo = await authInfoFc;
const orgInfo = await orgInfoFc;

计划2

let [userInfo, authInfo] = await Promise.all([this.getUser(), this.getAuth()]);

PS:
Promise.all 如果开发中,all 有一个失败了,如何使程序不走人catch中?

let [userInfo, authInfo] = await Promise.all([this.getUser(), this.getAuth()].map(p=>p.catch(e=>e)));

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理