【vue】for循环里嵌套了异步请求如何使它执行完了再执行下面代码

async uploadImg(file) {
   let formData= new FormData();
   formData.append("photo", file);
   const { data: data } = await uploadProductPicture(formData);
   console.log(data);
   this.imgName.push(data);
 },




async updateGood(state) {
      for (let i = 0; i < this.file.length; i++) {
      //MVP: await
        await this.uploadImg(this.file[i]);
      }
      console.log(this.oldPhoto.concat(this.imgName));
      const res = await updateBasicsProduct({
        id: this.goodId,
        name: this.newName,
        schoolId: this.newSchool,
        areaId: this.newArea,
        photos: this.oldPhoto.concat(this.imgName)
      });
      // console.log(res);
      if (res.code === 200) {
        this.$Message["success"]({
          background: true,
          content: "修改成功"
        });
        this.$router.push("/goods");
      }
    }
  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue中遍历数组并执行异步请求的方法有多种。根据提供的引用,有三种方法可以实现这个目标。 第一种方法是给forEach函数添加async关键字,并在forEach函数内部使用await关键字。但是这种方法会导致forEach外部无法获取到返回的值,因为forEach本身不支持async和await。 第二种方法是使用map函数,将每次异步请求包装成一个Promise,并将这些Promise保存在一个数组中。然后使用for...of循环等待每个Promise执行毕,最后可以在循环之外获取到返回的值。 第三种方法是使用async/await结合for...of循环。在for...of循环中使用await等待每次异步请求执行毕,并将结果存入数组中。最后可以在循环之外获取到返回的值。 以下是三种方法的具体实现示例: 方法一: async fetchDescription(data) { var arr = []; var prop = null; data.forEach(async (item) => { prop = await Description.fetch(item); arr.push(prop.data); }); console.log(arr); // => [] } 方法二: async fetchDescription(data) { var arr = []; var prop = null; let promises = data.map(async (item) => { prop = await Description.fetch(item); arr.push(prop.data); }); for (const promise of promises) { await promise; } console.log(arr); // => [e, e] } 方法三: async fetchDescription(data) { var arr = []; var prop = null; for (const item of data) { prop = await Description.fetch(item); arr.push(prop.data); } console.log(arr); // => [e, e] } 根据具体情况选择适合的方法来遍历数组并执行异步请求

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值