假设我有三个函数:
function A() {
//does a jquery getJson() request and applies json data to html
function C()
}
function B() {
//does a jquery getJson() request and applies json data to html
function C()
}
function C(){
// applies cosmetic changes to the already set html which was made be Functions A & B.
//for example it converts numbers 1-5 set in a span to starred rating.
}
问题是函数 A 和 B 是异步的,它们的回调执行取决于接收 json 所花费的时间。因此在 json 接收到的一个或另一个数据集上调用函数 C 失败。
所以我想要的是函数 C 应该在收到 json 并将其数据绘制到页面上之后执行。并且只需调用一次。
我觉得这可能通过闭包实现,但我不确定。
最佳答案
您可以使用 Deferred Object它为您处理异步调用。这样做你的代码将按阅读顺序执行,无论何时发回响应:
var jqxhr = $.getJSON('url', function(data) {
alert('first callback');
});
jqxhr.done(function() {
alert('second callback');
});
然后使用jQuery.when()
处理多个延迟:
var jqxhr1 = $.getJSON('url1');
var jqxhr2 = $.getJSON('url2');
$.when(jqxhr1, jqxhr2).done(function(data1, data2) {
alert('both done');
});
关于javascript - 等待多个条件然后执行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19474460/