javascript - JQuery .when 不在代码块之外工作

标签 javascript jquery ajax

我目前正在使用 Beaker Browser API,我需要向另一个用户的网站发出多个(至少 20 个)ajax 请求才能获取他们发布的内容。

我有以下数组:

var posts = []; // Where the data of the ajax is stored
var ajax_requests = []; // Where the ajax requests are stored
var following = []; // Where the urls for all requests are

以下逻辑循环遍历所有链接

// Get posts from all the people you follow
for(var i = 0; i < following.length; i++) {

    // Get the person's url and folders
    let person = new DatArchive(following[i]);

    // Read the directory containing all the posts
    person.readdir("/posts").then(files => {

        // For each post
        for(var j = 0; j < files.length; j++) {
            // Request the JSON object representing that post and add it to the array
            ajax_requests.push(get_posts(person.url + "/posts/" + files[j]));
        }
    });
}

get_posts() 函数和 .when:

function get_posts(url) {
    return $.ajax({
        type: "GET",
        dataType: "json",
        url: url,
        success: function(data) {
            console.log("Adding to posts");
            posts.push(data);
        }
    });
}    



$.when.apply($, ajax_requests).then(function() {
    console.log(posts.length);
});

我想要理解的是为什么 $.when 不等待 ajax 完成。我认为这就是它应该做的,相反它返回空数组。这就是一个,另一个就是为什么如果我将它移动到 person.readdir("/posts") block 内它就会起作用。

我不能把它留在那里,因为我想要进入的逻辑需要对 posts 数组进行排序并只显示其中的一部分,我认为这不应该是一个页面运行多次的东西负载。

最佳答案

您可以检查ajax_requests数组.length是否等于following.length乘以files.length在调用 $.when.apply()

之前

var following = [1, 2, 3];
var ajax_requests = [];

function get_posts(url) {
  return $.Deferred(dfd => 
    setTimeout(dfd.resolve, Math.floor(Math.random() * 1000), url));
}

for (var i = 0; i < following.length; i++) {

  // Get the person's url and folders
  let person = new $.Deferred(dfd => 
                 setTimeout(dfd.resolve, Math.floor(Math.random() * 1000)
                 , Array(3).fill(following[i]))
               );

  // Read the directory containing all the posts
  person.then(files => {

    // For each post
    for (var j = 0; j < files.length; j++) {
      // Request the JSON object representing that post and add it to the array
      ajax_requests.push(get_posts("/posts/" + files[j]));
      if (ajax_requests.length === following.length * files.length) {
        $.when.apply($, ajax_requests).then(function(...data) {
          console.log(data);
        });
      }
    }
  })
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>

关于javascript - JQuery .when 不在代码块之外工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47082277/

相关文章:

javascript - bitly API支持CORS吗?

javascript - 让用户滚动停止scrolltop的jquery动画?

javascript - 如何在 TinyMCE 中放置不可编辑的标签或 Div,以便它可以随文本滚动?

c# - 如何从 WCF 服务流下载文件?

jquery - 使用ajax加载框架

javascript - chrome 中的 SSRS 报告--报告未水平滚动

javascript - 删除不同域上的相同 cookie

javascript - 使用AJAX或预加载: dynamic changes of items in select element

javascript - 为每张图像设置不同的间隔

javascript - 无法更改 datetimepicker 的 minTime