这是我的一些代码:
for (var i = 0; i < recordList.length; i++) {
var recordID = recordList[i];
populateDataRow(i, recordID, columns)
};
console.log("done");
这里populateDataRow
是一个使用$.getJSON
的函数
问题是(至少在 Google Chrome 中),console.log
语句在 populateDataRow
周期完成
最佳答案
是的,console.log
首先发生,因为 getJSON
是异步。您的代码启动它,但它会在后续代码运行之后完成。
要处理这个问题,您需要在 getJSON
上使用“完成”回调。上面的代码会记住它启动了多少次调用,并在继续之前等待那么多次调用完成。
您还可以让您的 populateDataRow
函数返回 getJSON
的返回值,保存这些对象,然后使用 jQuery.when
当他们全部完成时收到通知。
这是一个示例:Live Copy | Live Source
var deferreds = [],
index;
for (index = 0; index < 4; ++index) {
deferreds.push($.getJSON("http://jsbin.com/agidot/1", function() {
display("One finished");
}));
}
$.when.apply($, deferreds).then(function() {
display("All finished")
});
function display(msg) {
$("<p>").html(String(msg)).appendTo(document.body);
}
请注意,只有当所有四个调用都完成时,我们才会看到“全部完成”。
对$.when
的调用有点麻烦。由于某种原因,您不能只将 Deferred
对象数组传递给其中。因此,我使用 Function#apply 来调用它,并将数组的每个条目作为离散参数传递。
令我惊讶的是 $.when
不接受数组并有效处理该数组,但我在这里看到其他答案也说使用 apply
: Here和 Here .
如果您要经常使用数组,我想我可能会将其包含在我的 jQuery 扩展的标准工具包中:
(function($) {
$.whenAll = function(deferreds) {
return $.when.apply($, deferreds);
};
})(jQuery);
...然后上面的代码示例的结尾将是:
$.whenAll(deferreds).then(function() {
display("All finished")
});
关于jquery - 如何仅在批量 getJSON 指令完成时触发某些操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16466702/