Vue使用for循环加Promise.all来发送多个请求,并且等到所有请求结束后处理数据

项目场景:

  1. 项目中要根据一个模型 id 的数组列表,来查询所有模型的数据
  2. 我需要对同一个接口循环发送多个请求,次数不定
  3. 必须等所有结果返回后,再处理数据,并展示

实现方法:

<script>
export default {
  data () {
    return {
      ids: [561, 562, 563, 564]
    }
  },

  methods: {
    createRecord (id) {
      return axios.post('/business/record', { id }).then((response) => {
        return response.data
      })
    }
  },

  mounted () {
    
    // 创建一个包含异步任务的数组,每个任务都是一个 axios 请求
    const arrays = []
    this.ids.forEach(id => {
      arrays.push(this.createRecord(id))
    })
    
    // 当所有请求都成功完成时,responses 是一个包含所有响应的数组
    Promise.all(arrays).then(responses => {
      console.log(responses)
    }).catch(error => {
      // 如果任何一个请求失败,将会进入这个 catch 块
      console.log(error)
    })

  }
}
</script>

响应结果:

[
    {
        "code": 200,
        "msg": "新增成功"
    },
    {
        "code": 200,
        "msg": "新增成功"
    },
    {
        "code": 200,
        "msg": "新增成功"
    },
    {
        "code": 200,
        "msg": "新增成功"
    }
]

猜你喜欢

转载自blog.csdn.net/u011690675/article/details/132833677
今日推荐