如何等待所有发布请求

时间:2020-04-06 13:17:27

标签: post axios

我有多个帖子请求,例如=>

for (var i = 0; i < this.state.selectedRowKeys.length; i++) {

      var rowid = this.state.selectedRowKeys[i];

      let savevalue = {
        id: rowid,            
      }
      queries.push(this.approve_leave(savevalue));
    }    


    Promise.all(queries).then(function (values) {
      console.log("done");         
    });

    this.selectData();
}

 approve_leave(savevalue) {       
    leave_api.leave_approve(savevalue).then(res => {         
      if (res.status === "fail") {           
        return false;
      }
      return true;
    })
  }

我调用了此发布API请求,并在完成所有发布请求之后,我只是从数据库中重新选择并在表中显示更新记录。

但是现在单击“保存”按钮后,它不会在表中显示刷新数据,但是如果重新加载页面,它将显示刷新数据。

Promise.all等待所有发帖请求,但

对于我来说,为什么它不等待所有请求并选择?

这是API请求=>

export const leave_approve = leave => {
  return axios
    .put(
      "http://127.0.0.1:8000/api/leave/leave_approve/",
      { leave },
      {
        headers: {
          "Content-Type": "application/json"
        }
      }
    )
    .then(res => res.data)
    .catch(error => {
      throw error;
    });
};

1 个答案:

答案 0 :(得分:0)

一段时间以来,我陷入了promise环回问题,现在我只需要asyn-await就可以完成上述所有工作。

样品:

async function something(){ // Should declare async in the method declaration to use await
// Below code waits till it is finished executing because we used await 
    await axios
    .put(
      "http://127.0.0.1:8000/api/leave/leave_approve/",
      { leave },
      {
        headers: {
          "Content-Type": "application/json"
        }
      }
    )
    .then(res => res.data)
    .catch(error => {
      throw error;
    });
}

https://javascript.info/async-await