• axios结合async await与promise的使用方法(异步转同步)


    场景:调用多个接口,需等待上一次请求完成,再调用下一个接口.(未二次封装axios)

    想利用async...await实现

    async created() {
        await this.getBank();
        ......
        await this.getAccountInfo();
        ......
      },

    请求函数写法如下:

    1.axios请求函数原生写法,无法将异步请求转为同步

    使用async await时无法将函数转为同步

    getCompanyList(pageNo, pageSizeNumber, val) {
                this.axios({
                    method: "post",
                    url: "api-acc/companyaccount/expand/getAccountCompanyList",
                    data: {
                        pageNo: pageNo,
                        pageSize: pageSizeNumber,
                        companyName: val
                    }
                })
                    .then(
                        response => {
                            if (!response.data.hasError) {
                                this.companyOptions = response.data.result.results;
                                this.total = response.data.result.total;
                            } else {
                            }
                        }
                    )
                    .catch(error => {});
            },

    2.使用promise,改造axios,可以结合async await 使用,可以将异步请求转为同步

    getProjectList() {
          //   console.log("getProjectList");
          return new Promise((resolve, reject) => {
            this.axios({
              method: "get",
              url: "/api-acc/accountprojectgrant/expand/granted",
            })
              .then((res) => {
                resolve(res);
                if (!res.data.hasError) {
                  let data = res.data.result;
                  this.projectListOptions = data;
                } else {
                  this.$message({
                    message: res.data.errorMsg,
                    type: "error",
                  });
                }
              })
              .catch((error) => {
                reject(error);
                this.$message.error("xxxx");
              });
          });
        },

    3.axios不单独写在请求函数中,直接结合async await使用,因为axios本身就是一个promise,此时也能将axios请求转为同步

     saveRunningWater(formName) {
          this.$refs[formName].validate(async (valid) => {
            if (valid) {
              this.saveInfoLoading = true;
              await this.axios({
                method: "post",
                url: "api-acc/accass/expand/assignaccass",
                data: {
                  id: this.runningWaterInfo.id,
                  projectId: this.runningWaterForm.projectId,
                },
              })
                .then((res) => {
                  if (!res.data.hasError) {
                    this.$message({
                      message: "保存成功",
                      type: "success",
                    });
                    this.runningWater = false;
                    this.getAcountInfo(); //刷新页面数据
                  } else {
                    this.$message({
                      message: res.data.errorMsg,
                      type: "error",
                    });
                  }
                })
                .catch((error) => {
                  this.$message.error("保存失败");
                });
              this.saveInfoLoading = false;
            } else {
              return false;
            }
          });
        },

    4.直接将请求函数return返回,return axios......也能将异步请求转为同步,因为axios本身也是基于promise

    getProjectList() {
          //   console.log("getProjectList");
          return  this.axios({
              method: "get",
              url: "/api-acc/accountprojectgrant/expand/granted",
            })
              .then((res) => {
                if (!res.data.hasError) {
                  let data = res.data.result;
                  this.projectListOptions = data;
                } else {
                  this.$message({
                    message: res.data.errorMsg,
                    type: "error",
                  });
                }
              })
              .catch((error) => {
                this.$message.error("xxxx");
              });
        },

    拓展:axios执行多并发请求

    处理并发请求的助手函数:

    axios.all(iterable)
    axios.spread(callback)
    function getUserAccount() {
      return axios.get('/user/12345');
    }
    
    function getUserPermissions() {
      return axios.get('/user/12345/permissions');
    }
    
    axios.all([getUserAccount(), getUserPermissions()])
      .then(axios.spread(function (acct, perms) {
        // 两个请求现在都执行完成
      }));

    也可以使用Promise.all(arr).then(res=>{ })

     this.$axios.all(arr).then((res)=>{})中then的第一个参数是一个数组,表示所有请求的信息;

     this.$axios.all(arr).then(this.$axios.spread(function (acct, perms){ }) 这种方式是请求返回的数据形式的数据逐个展开,acct表示请求返回后数组中的第一条数据,perms表示第二条数据;

  • 相关阅读:
    reids(缓存,reids下载,安装 测试)
    springboot(运行原理参考借鉴)
    springboot(整合事务和分布式事务)
    springboot(整合多数据源demo,aop,定时任务,异步方法调用,以及获取properties中自定义的变量值)
    Docker报错 WARNING: IPv4 forwarding is disabled. Networking will not work.
    springboot整合netty,多种启动netty的方式,展现bean得多种启动方法
    im开发总结:netty的使用
    学习中常见错误码得解决方案
    内部类的使用
    Variable used in lambda expression should be final or effectively final
  • 原文地址:https://www.cnblogs.com/younghxp/p/13414590.html
Copyright © 2020-2023  润新知