【问题标题】:Post request with axios one after another Vuejs一个接一个地用 axios 发布请求 Vuejs
【发布时间】:2020-02-14 09:01:46
【问题描述】:

我有 2 个发布请求,如果第一个被触发,第二个必须等待响应并执行发布请求。我读过一些关于 await 和 async 的东西,但不好。

let changed =false;

if(//something then){
    changed = true;
    axios.post('/uploadfile/' + id,  // This must be first
        formData,
    {
    headers: {
        'Content-Type': 'multipart/form-data',
    }
    })
    .then(function(response){
        // get response and do something
    })
    .catch(function(){
        //
    }); 
}

// if changed = true, then await for response from first post
axios.post('/uploadfile' + this.id_contract,  // If 
    data,
    {
    headers: {
        Authorization: getToken()
    }
})
.then(function(){
    // do something else
})
.catch(function(){
    //
});

【问题讨论】:

    标签: vue.js vuejs2 axios


    【解决方案1】:

    您可以像这样简单地使用 async/await:

    async myMethod() {
      let response1 = await axios.post('/1', ...)
      let response2 = await axios.post('/2', ...)
    }
    

    【讨论】:

      【解决方案2】:

      您可以将第二个调用与第一个请求的 .then 链接起来

      axios.post('/whatever').then((response) => {
          return axios.post('/whatever2'); 
      }).then((response) => {
          console.log('Response', response);
      });
      

      【讨论】:

        猜你喜欢
        • 2020-10-19
        • 2020-05-12
        • 2021-08-11
        • 2019-09-07
        • 2022-11-02
        • 2021-11-16
        • 2018-06-29
        • 1970-01-01
        • 2018-11-05
        相关资源
        最近更新 更多