• 【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
        },
  • 相关阅读:
    关于源码编译每次提示有错误 要make update-api
    如何在Android中添加系统服务
    git查看每个版本间的差异
    achartengine画出动态折线图
    java中基本数据类型和C语言中基本数据类型转换
    获取图片的真实宽高
    hdu-2066-一个人的旅行
    Linux内核模块编程与内核模块LICENSE -《具体解释(第3版)》预读
    Android平台Camera实时滤镜实现方法探讨(十一)--实时美颜滤镜
    ios9定位服务的app进入后台三分钟收不到经纬度,应用被挂起问题及解决方式
  • 原文地址:https://www.cnblogs.com/simawenbo/p/13536409.html
Copyright © 2020-2023  润新知