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

时间:2014-04-02 07:39:18

标签: javascript jquery callback

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.
}

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

1 个答案:

答案 0 :(得分:1)

无法逃避异步调用。您需要回调才能获得GET调用的结果。

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

这就是您的代码现在的工作方式。因此,响应始终为undefinednull

要从Ajax调用获取响应,请在调用函数时调用该函数,而不是为其分配响应。

function asyncCall(callBack) {
    var response;
    $.get(...) {
        response = someValueReturnedFromServer;
        callBack(response);
    }
    // There wont be a return here
}
asyncCall(function(response){
    // Do something with response now
});

这里的缺点是,如果您将arr对象(在您的代码中)传递给其他函数,即使必须更改为使用回调!

相关问题