如何使用promise.all()与async/await,实现多个接口并行查询,并等待最慢的接口返回成功,在继续执行后续代码的功能。

项目需求是,后台只提供字典单个查询接口,而页面中需要用到的字典较多,后续接口又需要等待全部字典请求完成,因此只使用await需要逐次请求字典接口13次,效率极低。

        因此结合promise.all(),对接口请求逻辑进行改造,以下是改造前代码:

data部分:

      dictArr: [
        {
          key: 'sglx' // 事故类型
        },
        {
          key: 'fxdj' // 风险等级
        },
        {
          key: 'xcpc' // 巡查频次
        },
        {
          key: 'fxkzlb' // 风险控制类别
        },
        {
          key: 'gkcj' // 管控层级
        },
        {
          key: 'fxys' // 风险因素
        },
        {
          key: 'wxyspzt' // 危险源审批状态
        },
        {
          key: 'gfx_in_or_open' // 高风险作业内部/公开
        },
        {
          key: 'gfx_irradiate_type' // 高风险作业照射类型
        },
        {
          key: 'gfx_gfxzyfj' // 高风险作业分级
        },
        {
          key: 'gfx_status' // 高风险作业创建的流程状态
        },
        {
          key: 'gfx_zyzt' // 高风险作业完成情况的流程状态
        },
        {
          key: 'gfx_sfwc' // 高风险作业完成情况是否完成
        }
      ],

method部分:

    // 查询所有字典
    async getAllDicts() {
      // 拿到字典类型统一查字典
      for (const dicItem of this.dictArr) {
        try {
          const { data } = await _getByTypeKeyForComBo(dicItem)
          this.hazardsDict[dicItem.key] = data
        } catch (error) {
          console.log(error)
          this.hazardsDict[dicItem.key] = []
        }
      }
    },

调用部分:

  async created() {
    this.loading = true
    await this.getAllDicts() // 数据字典接口(HazardsDictMixins)
    // await this.getUserList() // 用户数据接口(HazardsDictMixins)
    await this.getAllSites() // 场所数据接口(HazardsDictMixins)
    await this.getAllOrg() // 查询组织数据接口下拉树

    this.typeList1 = await this.handleQueryRiskTypeList() // 查询高风险作业分类(第一层级)

    this.getList()
  },

以下是改造后代码:

method部分:

    async getAllDicts() {
      // 拿到字典类型统一查字典
      try {
        const arr = []
        // 生成多个函数
        for (const dicItem of this.dictArr) {
          arr.push(_getByTypeKeyForComBo(dicItem))
        }
        // 并发执行,并等待最慢的执行完成
        Promise.all(arr).then((res) => {
          let i = 0
          for (const dicItem of this.dictArr) {
            this.hazardsDict[dicItem.key] = res[i].data
            i++
          }
        })
      } catch (error) {
        console.log(error)
      }
    },

代码改造以后,页面初次加载效率提升了2倍以上。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值