我正在寻找一种在两个 ajax 调用完成后进行回调的方法:
$.when(
call1(),
call2()
).always(function() {
// Here I want to be sure the two calls are done and to get their responses
);
要注意的是其中一个调用可能会失败。因此,在我的代码中,总是会调用而无需等待其他调用。
如何等待两个调用完成(成功或失败)?
最佳答案
这里有一些东西应该可以解决这个问题:
$.whenAllDone = function() {
var deferreds = [];
var result = $.Deferred();
$.each(arguments, function(i, current) {
var currentDeferred = $.Deferred();
current.then(function() {
currentDeferred.resolve(false, arguments);
}, function() {
currentDeferred.resolve(true, arguments);
});
deferreds.push(currentDeferred);
});
$.when.apply($, deferreds).then(function() {
var failures = [];
var successes = [];
$.each(arguments, function(i, args) {
// If we resolved with `true` as the first parameter
// we have a failure, a success otherwise
var target = args[0] ? failures : successes;
var data = args[1];
// Push either all arguments or the only one
target.push(data.length === 1 ? data[0] : args);
});
if(failures.length) {
return result.reject.apply(result, failures);
}
return result.resolve.apply(result, successes);
});
return result;
}
查看 this Fiddle看看它是如何工作的。
基本上它会等待所有 Deferred 完成,无论它们是否失败并收集所有结果。如果我们有失败,返回的 Deferred 将失败并列出所有失败,否则将返回所有成功。
关于javascript - jquery deferred - 等到两个调用完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15093145/