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

do something when nested async function is finished

本文关键字:操作 执行 完成时 嵌套 异步 函数      更新时间:2023-09-26
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

无法从异步调用中转义。您需要回调才能获得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对象(在您的代码中)传递给其他函数,即使必须将其更改为使用回调!