0

I know this has been asked many times.I have a Javascript function that need return result from a async call.

function IsValid(callback){
$.ajax({
url:...
success:(function(data){
callback(data);
});
};

IsValid(function(data){
//process returned data
};

Also I can use promise to do similar job. However, what I need is IsValid function must return a bool value, not process the result directly.i.e, I need

if (IsValid()) 
//process

because IsValid function will be called in different function and the process is different on each caller function.

Any help will be appreciated. Thanks.

Ziff
  • 9
  • 1
  • 5
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – JcDenton86 Feb 24 '17 at 11:02

1 Answers1

0

Use promises. jQuery returns a deferred object for AJAX calls, which acts like a Promise:

function IsValid() {
  return $.ajax({
    url:...
  });
}

IsValid().then(function(data) {
  // process returned data
});
Daniel T.
  • 37,212
  • 36
  • 139
  • 206