在jQuery 3中(参见问题),它看起来就像$.when
上的progress
改变了行为。我希望在每次延迟解决后得到进度通知:
var urls = [
'https://httpbin.org/delay/2',
'https://httpbin.org/delay/1'
];
console.log('started');
var deferreds = $.map(urls, function(url) {
var d = $.Deferred();
$.ajax({
url: url,
type: 'GET'
})
.always(function(){
console.log('done %o', url)
d.notify();
d.resolve.apply(this, arguments);
});
return d.promise();
});
$.when.apply(jQuery, deferreds).progress(function(){
// Does not call
console.log('progress?');
}).done(function(){
console.log('all done');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
代码也在码页上。当前产出:
“开始” “已完成https://httpbin.org/delay/1” “已完成https://httpbin.org/delay/2” “全部完成”
我希望在每个完成的请求之后看到一个progress?
输出。
用当前的jQuery API是否有一种很好的方法来实现这种行为?
发布于 2017-01-05 09:11:02
允许组件承诺通知聚合承诺:
考虑:
var urls = [
'https://httpbin.org/delay/2',
'https://httpbin.org/delay/1'
];
console.clear();
console.log('started');
var promises = urls.map(function(url, i) {
return $.Deferred(function(d) {
$.ajax({
url: url,
type: 'GET'
})
.always(function() {
console.log('done', i, url);
d.notify(i);
d.resolve.apply(this, arguments);
});
}).promise();
});
$.when.apply(null, promises).progress(function(x) {
console.log('progress ' + x);
}).done(function() {
console.log('all done');
});
在jQuery 1或2中,您可以合理地期望:
“开始” “完成1 https://httpbin.org/delay/1” “进展1” “完成0 https://httpbin.org/delay/2” “进展0” “全部完成”
但我明白:
“开始” “完成1 https://httpbin.org/delay/1” “未确定的进展” “完成0 https://httpbin.org/delay/2” “进展0” “全部完成”
天知道undefined
是从哪里来的。
现在,尝试交换两个urls的顺序-我得到:
“开始” “完成0 https://httpbin.org/delay/1” “进展0” “完成1 https://httpbin.org/delay/2” “进展0” “全部完成”
还是不像预期的那样--现在你得到了两次“进步0”!
IMHO,在jQuery 3中删除这一特性并不令人惊讶。
发布于 2017-01-05 05:00:12
请您尝试使用以下代码:
var urls = [
'https://httpbin.org/delay/2',
'https://httpbin.org/delay/1'
];
console.log('started');
var deferreds = $.map(urls, function(url) {
var d = $.Deferred();
$.ajax({
url: url,
type: 'GET',
success: function(){
d.notify(); //notify the progress handler about the current progress
}
})
.always(function(){
console.log('done %o', url)
d.resolve.apply(this, arguments);
});
return d.promise();
});
$.when.apply(jQuery, deferreds).progress(function(){
// Does not call
console.log('progress?');
}).done(function(){
console.log('all done');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div>
</div>
在这里,我们为ajax
添加了ajax
处理程序,通过该处理程序调用deferred.notify(),进展将通过该处理程序调用
https://stackoverflow.com/questions/41477408
复制相似问题