简体   繁体   中英

return from nested function after AJAX call

I have this situation where I have to check something via AJAX and then return the result. Or simplified:

function isValid() {
    $.ajax(URL, data, function(response) {
        isValid = response;
    });
    return isValid;
}

but still can't make it.

I can access the reponse, but I can't make isValid return AFTER I get the reponse. For example the solution I meet everywhere:

function isValid() {
    function checkOnServer(callback) {
        $.ajax(URL, data, function(response) {
            callback(response);
        });
    }
    checkOnServer(function(response) {
        alert(response);
    });
}

I met this all over Stackoverflow, BUT the problem is:

  1. I don't want to alert this.
  2. I want to RETURN it from isValid().

===========================

EDIT: I forgot to mention that if you/me/we try to simply "return" from the "checkOnServer" - it will just return it to the success callback of the AJAX. But the goal here is to make "isValid" return the result ... :)

your code is sensible ,but you use your callback function in isValid() so its doesn't alert !,also I've a little bit change your ajax function below

function isValid() { 
  checkOnServer(function(response) {
    alert(response);
  });
}
function checkOnServer(callback) {
    $.ajax({
         url : URL,
         data : data,
         success : function(response) {
           callback(response);
         }
     });
}

Edit

Variable is can't return from asynchronous method ?If we call function with ajax ,call function is run first immediately before ajax is response,so it will return undefined only with above method.

There is two method I've know to return from asynchronous function

Call after ajax function is done

 function isValid() {
  var data; 
  checkOnServer(function(response) {
    data = response;
  });
  return data;
}
function checkOnServer(callback) {
    $.ajax({
         url : URL,
         data : data,
         async : false             
     }).done(function(response){
        callback(response);
        });
}
console.log(isValid());

Assign variable with responseText

 function isValid() { 
 var data = checkOnServer();
 return data;
}
function checkOnServer() {
    var data = $.ajax({
                 url : URL,
                 data : data,
                 async : false //must set async to false
              });
    return data.responseText;
}
console.log(isValid());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM