$.when.apply.done 不执行异步函数

$.when.apply.done not executing asynchronous functions

本文关键字:执行 异步 函数 done when apply      更新时间:2023-09-26

我必须在所有异步函数完成执行后执行一个回调函数。
为此,我创建了一个包含异步函数的数组:

var funcs = [];
var requests = [];

我在其中推送了一些 ajax 函数。

这是我的解决方案,它不起作用:

for(i = 0; i < functions.length; i++){
  var f = functions[i](); //calling each ajax functions
  requests.push(f);
}    
$.when.apply(null, requests).done(function(){
    console.log("Hello");
});

现在函数正在异步执行,但在函数执行完成之前调用回调函数。

我推送的 ajax 函数示例之一:

functions.push(function () {
  return $.ajax({
    url: "some url",
    success: function(){
    console.log("Finished execution");
  }
});

您的匿名函数没有return,因此其有效返回值为 undefined

因此,首先您需要修复匿名函数以包含return

functions.push(function() {
     return $.ajax(...);
});

您还可以对调用循环进行更简洁的实现:

var requests = functions.map(function(f) {
    return f();
});
$.when.apply($, requests).done(callb);