我目前正在使用 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/