Justin
Justin

Reputation: 45350

JavaScript Asyn Returns Without Waiting For Response

I have a JavaScript function which makes an ajax request, and depending on the result either returns true or false.

The problem is when I am calling the function it is immediately returning, without waiting for the ajax request to fire and really return the right response. How do I handle this?

function check_value() {
   //Pseudo code
   ajax('some-url.php', function(response) {
      if(response.success) {
         return true;
      } else {
         return false;
      }
   });
}

if(check_value()) {
   alert("true");
} else {
   alert("false");
}

See the problem? check_value() is executing and returning immediately, before the AJAX request fires and calls the callback.

Upvotes: 0

Views: 100

Answers (1)

Joel Lundberg
Joel Lundberg

Reputation: 916

That is the inherent nature of an asynchronous call, you never know when it will be done. So instead create two handlers for success and error:

function check_value() {
   //Pseudo code
   ajax('some-url.php', function(response) {
      if(response.success) {
         handleSuccess();
      } else {
         handleError();
      }
   });
}

function handleSuccess() {
    alert('true');
}

function handleError() {
    alert('false');
}

Upvotes: 1

Related Questions