Waiting for POST request to finish before GET request starts (React/Node)

I have been trying for ages to fix this myself but I have given up. I am using React and Node to:

  1. Send text from React to Node
  2. Modify the text in Node
  3. Send the modified text back to React

It all works fine if I click to start the POST request, wait a second, then click a different button to start the GET request, but I am trying to do it all from one command. My problem is that the GET request often finishes first, so my question is: How do I make sure the POST request finishes before the GET request starts.

I have tried this, but to no avail:

  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();
      }

Answer

Try having await before get request.

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

Additionally, you need to update your postReq method as well, in order to await for the axios call returns with resolved promise. Otherwise, return Finished will be called before finishing the post request. (Therefore use async/await for postReq as well)

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";
};