【问题标题】:Waiting for POST request to finish before GET request starts (React/Node)在 GET 请求开始之前等待 POST 请求完成(React/Node)
【发布时间】:2021-09-02 10:36:52
【问题描述】:

多年来我一直在尝试自己解决这个问题,但我已经放弃了。我正在使用 React 和 Node:

  1. 从 React 向 Node 发送文本
  2. 修改Node中的文字
  3. 将修改后的文本发送回 React

如果我单击启动 POST 请求,等待一秒钟,然后单击另一个按钮启动 GET 请求,一切正常,但我试图通过一个命令完成所有操作。我的问题是 GET 请求通常先完成,所以我的问题是:如何确保 POST 请求在 GET 请求开始之前完成。

我试过了,但没有用:

  postReq = () => {
    if(this.state.theUrl.length > 0) {
    axios.post('http://localhost:5000/check', {
      url: this.state.theUrl
    }).then(function(response) {
      console.log("Success")
    }).catch(function(error) {
      console.log(error)});
    }
    else {
      return 1;
    }
    return "Finished"
  }
  
  getReq = () => {
      axios.get('http://localhost:5000/check')
      .then((getResponse) => {
        this.setState({summaryParts: getResponse.data, postResponse: ""})});
  };

   callApi = async() => {
         const result = await this.postReq();
           this.getReq();
      }

【问题讨论】:

  • 你能分享一下postReq的样子吗

标签: reactjs express asynchronous async-await


【解决方案1】:

尝试在get 请求之前使用await

callApi = async () => {
  const result = await this.postReq();
  await this.getReq();
};

此外,您还需要更新 postReq 方法,以便 await 让 axios 调用返回并返回已解决的承诺。否则,return Finished 将在完成发布请求之前被调用。 (因此async/await 也用于postReq

postReq = async () => {
  if (this.state.theUrl.length > 0) {
    /* await for the request to be finished */
    await axios 
      .post("http://localhost:5000/check", {
        url: this.state.theUrl,
      })
      .then(function (response) {
        console.log("Success");
      })
      .catch(function (error) {
        console.log(error);
      });
  } else {
    return 1;
  }
  return "Finished";
};

【讨论】:

  • 成功了!看了你的解释,我完全明白我哪里错了,非常感谢!
【解决方案2】:

添加异步并返回

postReq = async () => {
if(this.state.theUrl.length > 0) {
return axios.post('http://localhost:5000/check', {
  url: this.state.theUrl
}).then(function(response) {
....

【讨论】:

  • 请在您的回答中提供更多详细信息。正如目前所写的那样,很难理解您的解决方案。
猜你喜欢
  • 2020-03-04
  • 2016-08-04
  • 1970-01-01
  • 2018-12-05
  • 1970-01-01
  • 2022-11-07
  • 2016-09-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多