1

I've got an ajax call and on success, I increment the value of received by 1. getMessage() should only been entered whilst received < 10 is true. However, the return of received outside of the function is always 0, resulting in an infinite while loop.

Anyone have any suggestions so that the updated received value can be seen outside of the function?

var received = 0;

while (received < 10) {
    getMessage();
}

function getMessage() {
    $.ajax({
        url: '/Home/getData/',
        type: "GET",
        success: function(result) {
            received += 1;
        }
    });
    console.log(received);
}
}
});
}
Yadu
  • 103
  • 1
  • 14
  • 6
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Taplar May 15 '18 at 14:17
  • The shortest solution to this would be to turn the while loop into an if conditional in the success handler. – Taplar May 15 '18 at 14:18
  • @Taplar the first time it's executed, it will not execute again –  May 15 '18 at 14:23
  • If it's inside the success method it will – Taplar May 15 '18 at 14:23
  • The ajax call, and therefore your `getMessage()` function, returns immediately and executes asynchronously. So your `while` loop will call `getMessage()` many times before the first call has succeeded and called the `success` function. – peeebeee May 15 '18 at 14:30

1 Answers1

1

I would highly recommend reading the duplicate post. However, this is one possible solution to your issue with trying to use asynchronous methods.

var received = 0;

//received is < 10, start loop
getMessage();

function getMessage() {
  $.ajax({
    url: '/Home/getData/',
    type: "GET",
    success: function(result) {
      received++; //increment
      
      if (received < 10) {
        console.log(received);
        getMessage();
      }
    }
  });
}
Taplar
  • 24,788
  • 4
  • 22
  • 35