'How to use data from an ajax.done to stop a while loop

I have a while loop that does an ajax request to the backend and I want to use data from the backend response to decide when to get out of the while loop. Something like in the code below. The code below doesn’t work because the breakout variable is not accessible outside the request.done method. So I tried to update an html tag from inside the request.done method then try to use this tag to break out of the while loop but this did not work either.

while(true) { 
  request = $.ajax({
    ‘url’:’some url’,
    ‘Method’:’GET’
  });
  request.done(fuction(data) { 
    var this_value = data['break']
    if(this_value = "name") { 
      break;
    }
  });


Solution 1:[1]

The code below doesn’t work because the breakout variable is not accessible outside the request.done method.

No, that is not the reason. The reason is that:

  • The done callback never executes, because the engine is forever busy running the while loop, not ever processing the event queue, where the event is sitting that would instruct the engine to call the done callback. This also explains why your other attempt with the HTML element didn't help.

  • break is invalid where you have it, because it occurs in a function where there is no loop to break from.

  • The code has several other syntax errors.

You would need to deal with the asynchronous nature of the done callback. It can only execute when the while loop ends, and so you should have no while (true) to begin with.

Here is how it could work:

let url = "https://www.random.org/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new";

function loop() {
  let request = $.ajax({
    url,
    Method: 'GET'
  });
  request.done(function (data) { 
    console.log(data);
    if (data == 10) return; // break condition
    loop(); // repeat
  });
}

loop();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

In more modern JavaScript, you'd use the fetch API and async/await, and then you can use while again, simply because await suspends the function execution context:

let url = "https://www.random.org/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new";

(async function () {
  while (true) {
    let request = await fetch(url);
    let data = await request.json();
    console.log(data);
    if (data == 10) break; // break condition
  }
})();

Sources

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

Source: Stack Overflow

Solution Source
Solution 1 trincot