axios同步请求--

本文详细介绍了如何在Vue项目中使用async/await实现Axios的同步请求,包括封装请求函数和处理响应的方法,并展示了在实际页面操作中的应用案例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一般使用axios进行数据请求就是要使用异步请求,因为项目需求,需要同步请求,所以async+await了解一下:
async用于声明一个函数是异步的,await用于声明在一个异步函数中等待语句执行完毕。也就是说await只能在async函数中使用
基本用法就是这样的:

methods: {
    async funA(){
        var res =  await axios.post('') //这里的res就是axios请求回来的结果
    }
}

我这边是用在项目里的
common.js

async addImg(file, config) {
    return await axios.post(path.addImage, file, config);
  }

vue页面

methods:{
async upload() {
      var self = this;
      var formData;
      for (let i = 0; i < this.imgList.length; i++) {
        const img = this.imgList[i];
        formData = new FormData();
        formData.append("file", img);
        formData.append("type", "goods_grade");
        console.log(formData.getAll("file"));
        await this.$api.common
          .addImg(formData, {
            headers: { "Content-Type": "multipart/form-data" }
          })
          .then(res => {
            if (res.data.code == 200) {
              this.$message({
                type: "success",
                message: "添加成功"
              });
              this.uploadSuccess = true;
              this.childrenImgs.push(res.data.result);
              this.$emit("change", this.childrenImgs);
            } else {
              this.$message({
                type: "warning",
                message: res.data.message
              });
            }
          });
      }
    }
}

注意事项
如果同步请求是封装在其他函数中,那么每一个函数都需要做成异步函数。如下所示

methods: {
  fun1: async function () {
    await axios.get('url)
  },
  fun2: async function () {
    ...
    await this.fun1()
    ...
  },
  fun3: async function () {
    ...
    await this.fun2()
    ...
  },
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值