优化前
多个接口await串行请求,若一个接口用时1秒,3个接口一共得用时3秒才行
async asyncData() {
let res1 = await danielService.getAllDanielByIndex();
let res2 = await journalService.getJournalType();
let params = {
page: 1,
pagesize: 10,
};
let res3 = await journalService.queryJournal(params);
return {
danielList: res1?.data?.data || [],
typeList: res2?.data?.data || [];,
sortList: res3?.data?.data?.list || [],
};
},
优化后
多个接口await并行请求,若一个接口用时1秒,3个接口一共也就用时1秒
async asyncData() {
const data = {
danielList: [],
typeList: [],
sortList: [],
};
let params = {
page: 1,
pagesize: 10,
};
try {
const [res1, res2, res3] = await Promise.allSettled([
danielService.getAllDanielByIndex(),
journalService.getJournalType(),
journalService.queryJournal(params),
]);
if (res1.status === "fulfilled") {
data.danielList = res1.value?.data?.data || [];
}
if (res2.status === "fulfilled") {
data.typeList = res2.value?.data?.data || [];
}
if (res3.status === "fulfilled") {
data.sortList = res3.value?.data?.data?.list || [];
}
} catch (error) {
console.error(error);
}
return data;
},
参考文档
Promise相关语法:https://juejin.cn/post/7250383386183221285
标签:res1,请求,nuxt2,res2,res3,await,接口,data From: https://www.cnblogs.com/huihuihero/p/18362545