nuxt2 优化asyncData 里多个接口await串行请求的弊端,改为并行请求

优化前

多个接口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,
    };
    await Promise.allSettled([
      danielService.getAllDanielByIndex(),
      journalService.getJournalType(),
      journalService.queryJournal(params),
    ])
      .then((res) => {
        const [res1, res2, res3] = res;
        if (res1.status === "fulfilled") {
          data.danielList = res1.value?.data?.data || [];
        }
        if (res2.status === "fulfilled") {
          data.typeList = res2.value?.data?.data["Academic"] || [];
        }
        if (res3.status === "fulfilled") {
          data.sortList = res3.value?.data?.data?.list || [];
        }
      })
      .catch((error) => {
        console.error("error", error);
      });
    return data;
  },

参考文档

Promise相关语法:https://juejin.cn/post/7250383386183221285

posted @ 2024-08-16 11:33  huihuihero  阅读(34)  评论(0编辑  收藏  举报