Daniel
Daniel

Reputation: 4342

repeat function until true

I am trying call an ajax request until it returns a true value. I have tried the following code but it does not return any results and no errors in the console. Any idea what I am doing wrong?

function getUserData() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://api.example.com/data.json", true);
xhr.onreadystatechange = function() {
  if (xhr.readyState == 4) {
    var resp = JSON.parse(xhr.responseText);
    return resp.status;
  }
}
xhr.send();
}

setInterval(function () {
if (getUserData() === "true") {
   alert("true");
}
}, 10000);

Upvotes: 3

Views: 8031

Answers (3)

Josh
Josh

Reputation: 44916

Yes, your function is going to return immediately, but will always return undefined.

Since the operation is asynchronous you need to rewrite it to be based on a callback.

function getUserData(callback) {
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://api.example.com/data.json", true);
xhr.onreadystatechange = function() {
  if (xhr.readyState == 4) {
    var resp = JSON.parse(xhr.responseText);
    callback(resp.status);
  }
}
xhr.send();
}

setInterval(function () {
var isTrue = "false";

while(isTrue !== "true"){
   getUserData(function(result){ isTrue = result });
}

}, 10000);

Upvotes: 0

Akhil Sekharan
Akhil Sekharan

Reputation: 12683

Since you are calling it async, you can't return a value from function. Try this:

function getUserData() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://api.example.com/data.json", true);
xhr.onreadystatechange = function() {
  if (xhr.readyState == 4) {
    var resp = JSON.parse(xhr.responseText);
    if (resp === "true")
        alert("true");
    else
        getUserData();
  }
}
xhr.send();
}

Upvotes: 0

beatgammit
beatgammit

Reputation: 20225

getUserData calls an asynchronous function internally, so it has returned long before the AJAX call is actually finished.

Instead of doing this in a setInterval loop, you might want to try calling getUserData again in the failure case. For example:

function getUserData() {
    var xhr = new XMLHttpRequest();

    xhr.open("GET", "http://api.example.com/data.json", true);
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            var resp = JSON.parse(xhr.responseText);
            if (resp.status) {
                alert("true");
            } else {
                setTimeout(getUserData, 10000);
            }
        }
    }
    xhr.send();
}

getUserData();

Upvotes: 5

Related Questions