在vue中循环中调用接口-promise.all();按顺序执行异步处理

本文介绍如何在Vue项目中使用Promise.all()进行批量异步请求,并通过实例展示了如何确保一系列异步操作按顺序执行,从而提高前端应用的性能和用户体验。

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

  1. 在vue中循环调用接口-promise.all()
methods: {
  handleAdd (arr) {
     this.loading = true
     const allApi = []
     arr.forEach((item, index) => {
       const data = {
         id: item.id,
         name: item.name
       }
       const oneApi = api.add(data).then(res => {
         if (res.error_code === 0) {
           this.$message.success(res.msg)
         } else {
           this.$message.error(res.msg)
         }
       })
       allApi.push(oneApi)
     })
     Promise.all(allApi).then(() => {
       this.loading = false
     })
   }
}
  1. 有异步处理数据时,按顺序执行函数
methods: {
	handleAdd (val) {
        this.addTag(val).then(() => {
          this.tags.push(this.newTag)
          this.editNote()
        })
    },
	addTag (val) {
      const data = {
        tag: val
      }
      return add(data).then(res => {
        this.newTag = {
          id: res.data.id,
          name: res.data.name
        }
      })
    },
    editNote () {
      const data = {
        tags: this.tags,
      }
      update(data).then((res) => {
        if (res.error_code === 0) {
          this.$message.success('修改成功!')
         }
      })
    }
}

使用return返回第一个异步处理的结果;使用then,继续执行第二个异步处理(当第一次返回结果为ture时)。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值