Javascript 完成嵌套异步函数后执行某些操作

Javascript 完成嵌套异步函数后执行某些操作,javascript,jquery,callback,Javascript,Jquery,Callback,如何确保在返回前填充了arr?无法逃避异步调用。您需要回调以获取get调用的结果 function hello() { var arr = []; $.get(url, function (data) { var items = $(data).find("item"); $(items).each(function (idx, item) { arr.push(item); }); }); return arr; //

如何确保在返回前填充了
arr

无法逃避异步调用。您需要回调以获取
get
调用的结果

function hello() {
   var arr = [];
   $.get(url, function (data) {
      var items = $(data).find("item");
      $(items).each(function (idx, item) {
        arr.push(item);
      });
   });
   return arr; //undefined because nested loops are not finished processing.
}
这就是您的代码现在的工作方式。所以响应总是
未定义

要从Ajax调用获取响应,请在调用函数时将回调传递给函数,而不是为其分配响应

function asynCall() {
    var response;
    // Ajax call will update response here later.
    return response;
}
var responseFromFun = asyncCall(); // This will be undefined or null.

这里的缺点是,如果要将
arr
对象(在代码中)传递给其他函数,甚至必须更改该函数以使用回调

嘿,谢谢你。在遇到这个问题之前,我想我并不真正理解回调是如何构造的。现在我知道了!还有一个问题要补充。为什么有必要检查callback是否是一个类似于
typeof callback==“function”
的函数,就像在其他一些与回调相关的帖子中看到的那样?@MaximusS只是为了确保确实传递了一个函数,而不是一个数字或任何东西。在上面的代码中,
asyncCall(“hello”)
也是有效的,但在
get
调用完成时会导致错误,因为没有完成错误处理。
function asyncCall(callBack) {
    var response;
    $.get(...) {
        response = someValueReturnedFromServer;
        callBack(response);
    }
    // There wont be a return here
}
asyncCall(function(response){
    // Do something with response now
});