我有一组 promise ,我正在尝试添加一个回调,当所有这些都成功时将执行该回调。这是 jQuery $.when()
的主要用例,但它无法正常工作。
我为几个不同的 ajax 查询运行了这段代码:
// Global variable that holds the promises
var dygraph_promises = []
var plot_promise = $.ajax()
plot_promise.done(function(a) {
console.log("DONE!");
// do stuff with data
});
// Keep track of promises
dygraph_promises.push(plot_promise);
然后我想在一切完成后运行下面的代码
// Synchronize dygraphs together
console.log(dygraph_promises);
console.log(dygraph_promises.length);
$.when.apply($, dygraph_promises)
.then(function() {
console.log("when called!");
});
当我在控制台中运行此代码时,我看到字符串 "when called"
打印在字符串 "DONE"
之前。所以 when
在所有调用完成之前触发..
知道为什么这不起作用吗?
最佳答案
感谢@adeneo 的帮助,我发现我没有使用标准的 jQuery promises。结果,我开始使用 q.js库,并使用 all
调用 there
Q.all(dygraph_promises)
.then(function(a) {
...
)};
关于javascript - jquery - 当一系列 promise 成功时运行回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29956374/