return from nested function after AJAX call

前提是你 提交于 2020-01-07 05:29:05

问题


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 ... :)


回答1:


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());


来源:https://stackoverflow.com/questions/35508182/return-from-nested-function-after-ajax-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!