'JavaScript - How to send multiple XMLHttp requests or force the XMLHTTP request to wait till I get the desired response?

I am making a GET request to the api using XMLHttpRequests. The api takes in a "uuid" value denoted by the variable "a" here as a parameter, uses that value for processing and is supposed to spit out some information that I am trying to print to the console.

However, the problem I am running into is that, whenever the api successfully receives the uuid value it returns a message where the newresponse.response.status is Initiated. However I want to wait till the newresponse.response.status is Success (this usually takes a short bit like 3-4 seconds more).

The original code is shown below:

function getrequestresults(status, response) {
  let parse = JSON.parse(response);
  let a = parse.uuid;
  let newrequest = new XMLHttpRequest();
  newrequest.open('GET', "http://localhost:5000/api/v1/dags/results" + "?" + "uuid" + "=" + a, true);
  newrequest.onload = function() {
    //console.log(newrequest.status);
    console.log(newrequest.response);
  };
  newrequest.send();
}

One of the attempts I made at fixing this was as follows:


function getrequestresults(status, response) {
  let parse = JSON.parse(response);
  let a = parse.uuid;
  let newrequest = new XMLHttpRequest();
  newrequest.open('GET', "http://localhost:5000/api/v1/dags/results" + "?" + "uuid" + "=" + a, true);
  newrequest.onload = function() {
    while (newrequest.response.status != "Success") {
      //the following line was just to see what's going on, idea was to keep looping till, desired status is reached
      console.log(newrequest.response);
    }
    //console.log(newrequest.status);
    console.log(newrequest.response);
  };
  newrequest.send();
}

However, this did not work as it seems that the "onload" function only runs once, whereas I need it to run multiple times until newrequest.response.status is Success.

I am quite new with sending XMLHttpRequests and some help would be appreciated. Thanks.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source