javascript - 所有 ajax 调用完成后如何运行函数

标签 javascript jquery ajax

假设我有这个功能:

function testAjax(url) {
  return $.ajax({
    url: url,
    type: 'GET'
  });
}

现在我有很多节点(我正在使用D3),我希望循环遍历。每个文件可能有也可能没有关联的一些文件。为了查明是否存在,我获取所选节点上的 url,检查返回的数据,如果它有一个/多个文件,我将其添加到文件数组中。然后,我希望仅在遍历每个节点并检查它以查看它是否有文件后才记录文件数组。

其余代码与此类似:

var allFiles = [];
nodes.each(function(d) {
      testAjax(d.url)
        .success(function(data) {
          if (data.files) {
            if (data.files.length > 0) {
              for (var i = 0; i < data.files.length; i++) {
                allFiles.push(data.files[i])
              }
            }
          }
        })
    })
//Here is where I want to log/use (call a function passing the files array as an argument) the array of files after its been completed.

最佳答案

创建 Promise 数组并使用 $.when()解析完整数组后进行解析

var allFiles = [];
var promises = [];

nodes.each(function(d) {
   // reference to promise
   var req=  testAjax(d.url)
        .success(function(data) {
          if (data.files) {
            if (data.files.length > 0) {
              for (var i = 0; i < data.files.length; i++) {
                allFiles.push(data.files[i])
              }
            }
          }
        })
    });
   // push to array
   promises.push(req);
});
$.when.apply(null, promises).then(function(){
    // all promises have been resolved here

}).fail(function(){
    alert('Opps ... something went wrong with one of the requests')
})

关于javascript - 所有 ajax 调用完成后如何运行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38459926/

相关文章:

javascript - Flash 支持与安装的 Flash

php - 将 PHP 变量动态传递给 AJAX JavaScript 函数

php - 这个 jQuery 选择器的问题

托管时网站上不加载 Javascript/CSS 文件

javascript - 为什么这个切换和过滤器在 Vue JS 中不起作用?

javascript - 在文档就绪时根据 URL 参数选择选项并检查复选框的功能

javascript - 使 jQuery 线条动画在滚动上移动

javascript - 如何点击 Chrome 扩展程序中的按钮

jquery - 在 jQuery 中使用 .css 属性

javascript - html、javascript - 弹出窗口