zoukankan      html  css  js  c++  java
  • 【Vue】 axios同步执行多个请求

    问题

    项目中遇到一个需求,在填写商品的时候,选择商品分类后,加载出商品分类的扩展属性。

    这个扩展属性有可能是自定义的数据字典里的单选/多远。

    要用第一个axios查询扩展属性,第二个axios 从第一个axios中获得的code值去查询 数据字典。

    解决思路

    我是net后端开发,之前没有接触过Vue,也没用过axios,以前使用ajax是 直接加async:false属性就能同步执行。

    在axios中没有这个属性,经过一番查找,发现可以使用ES8新特性 async/await 解决,类似于c#的异步,用法差不多。

    具体的用法是 在需要实现同步的方法前面+async 使用方法的时候前面+ await。

    然而我发现这样写第一个axios  async是失效的,如下图所示,百思不得其解。

    询问前端大佬才发现这个函数是一个匿名函数,真正需要等待的是then后面的函数,async需要加在then后面。修改后,问题解决。

    示例代码

    第一个axios:

    // async callApiWithPost('/Owner_Manage/Goods_Extend/GetAllExtendBySortIds', this.groupIds).then((resJson) => {
    callApiWithPost('/Owner_Manage/Goods_Extend/GetAllExtendBySortIds', this.groupIds).then(async(resJson) => {
              if (resJson.Data !== null && resJson.Data.length > 0) {
                for (var index = 0; index < resJson.Data.length; index++) {
                  let codeList = []
                  // 如果扩展属性 Type = 4 || 5 ,则执行同步axios方法,查找该扩展属性的字典项,加载到tableData中
                  if (resJson.Data[index].Type === 4 || resJson.Data[index].Type === 5) {
                    codeList = await this.$options.methods.getCodeList(resJson.Data[index].Code)
                  }
                  this.$refs.tableValue.tableData.push({
                    ExtendId: resJson.Data[index].Id,
                    Name: resJson.Data[index].Name,
                    Type: resJson.Data[index].Type,
                    codeList: codeList
                  })
                }
              }
            }).catch((e) => {
              console.log('获取分类数据失败')
            })

    第二个axios:

    async getCodeList(code) {
          const codeList = []
          await callApiWithPost('/BaseInfo_Manage/Base_Code/GetCodeListByType', { id: code.trim() })
            .then((resJson) => {
              if (!resJson.Data || Object.keys(resJson.Data).length === 0) {
                this.$message.error('未查询到数据或数据为空')
              } else {
                for (var m = 0; m < resJson.Data.length; m++) {
                  codeList.push({ id: resJson.Data[m].Id, name: resJson.Data[m].Name })
                }
              }
            }).catch((e) => {
              console.log('获取字典项数据失败')
            })
          return codeList
        },
  • 相关阅读:
    9。11
    9.9样式
    9.9 容我懵逼一会
    16.9.8
    16.9.6下午
    16.9.6上午
    16.9.5下午
    流程例子
    使用极酷阳光播放器做流媒体播放并不暴露视频地址
    php 文件限速下载代码
  • 原文地址:https://www.cnblogs.com/simawenbo/p/13536409.html
Copyright © 2011-2022 走看看