如何用axios循环发起请求

### 问题描述
循环发送axios post请求,post请求时间可能长达60秒或更多

### 问题出现的环境背景及自己尝试过哪些方法
用for循环发起axios请求,post参数number始终为空

### 相关代码

    PostAll: function() {
      for (var k in this.myListFilter)
        {console.log("myListFilter: " + this.myListFilter[k][0]);
        this.allNumber = this.myListFilter[k][0];
        console.log("allNumber: " + this.allNumber);
        this.$options.methods.PostAllEach();
        }
    },
    PostAllEach: function () {
      axios.post(url, {
          input: {
            param: {
              method: "Update All",
              number: this.allNumber
            }
          }
        }
      ).then(
        this.allNumber = ""
      )
  }

### 你期待的结果是什么?实际看到的错误信息又是什么?

  1. 循环发起axios请求
  2. 如果循环结束则显示一条结束消息(应该如何实现?)
阅读 6.2k
2 个回答

使用ES6的Promise,处理异步请求看看

PostAll: async function() {
  for (var k in this.myListFilter)
    {console.log("myListFilter: " + this.myListFilter[k][0]);
    this.allNumber = this.myListFilter[k][0];
    console.log("allNumber: " + this.allNumber);
    await this.$options.methods.PostAllEach();
  }
},
PostAllEach: function () {
  return new Promise((resolve, reject) => {
      axios.post(url, {
          input: {
            param: {
              method: "Update All",
              number: this.allNumber
            }
          }
        }
      ).then(res => {
        resolve(res)
      }).catch(error => {
        reject(error)
      })
  })
}

['/api/xxx','/api/xxx'].reduce((c,n)=>c.then(res=>axios.post(n)),Promise.resolve())

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题