【发布时间】:2015-01-21 18:24:40
【问题描述】:
我正在使用 jQuery 发出各种 ajax POST 请求。我需要跟踪每个请求的成功或失败,以及整个批次的整体进度,以便我可以使用进度条和有关成功请求的数量以及成功请求的信息来更新 UI失败,不在总数中。
在尝试在我的应用程序中实现该功能之前,我一直在使用 jsfiddle 中的一些代码作为概念证明,但到目前为止没有运气。这就是我所拥有的:
// an alternative to console.log to see the log in the web page
var fnLog = function(message) {
$('#console').append($("<p>" + message + "</p>"));
};
// keeping track of how many ajax calls have been finished (successfully or not)
var count = 0;
// a dummy ajax call that succeeds by default
var fn = function(shouldFail) {
return $.get(shouldFail ? '/echo/fail/' : '/echo/json/')
.done(function() { fnLog("done") })
.fail(function() { fnLog("FAIL") });
};
// a set of different asynchronous ajax calls
var calls = [fn(),fn(),fn(),fn(true),fn(),fn()];
// an attempt to make a collective promise out of all the calls above
$.when.apply($, calls)
.done(function() { fnLog("all done") })
.fail(function() { fnLog("ALL FAIL") })
.always(function() { fnLog("always") })
.progress(function(arg) { fnLog("progress" + arg) })
.then(function() { fnLog("finished") });
这一切都在这个小提琴中:http://jsfiddle.net/mmtbo7v6/1/
我需要的是能够提供一个回调,在所有的 Promise 都解决后(无论成功与否)都应该调用该回调。
当上述所有调用都设置为成功时(通过将true 参数删除到数组中的第四个fn 调用),它可以正常工作。输出打印以下内容:
done
done
done
done
done
done
all done
always
finished
但是,即使单个调用设置为失败(因为它在 jsfiddle 中默认设置),输出如下:
done
FAIL
ALL FAIL
always
done
done
done
done
因此,在解决所有承诺后,不会调用任何集体承诺回调(由$.when 调用生成的回调)。如果单个 ajax 调用失败,则根本不会调用最终的 .then。
此外,我希望了解如何跟踪这批 ajax 调用的进度,以更新 UI 中的进度条。
【问题讨论】:
标签: javascript jquery ajax progress-bar promise