在jQuery 3中(请参阅issue),$.when
上的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>
&#13;
progress?
&#13;
代码也在codepen上。当前输出:
&#34;开始&#34;
&#34;完成https://httpbin.org/delay/1&#34;
&#34;完成https://httpbin.org/delay/2&#34;
&#34;全部完成&#34;
我希望在每个完成的请求后看到<Directory "D:/Prject1Alias/Uploads/">
Options Indexes FollowSymLinks Includes ExecCGI
AllowOverride all
Order Allow,Deny
Allow from all
</Directory>
输出。
使用当前的jQuery API有一种很好的方法来实现这种行为吗?
答案 0 :(得分:1)
允许组件承诺通知聚合承诺:
考虑一下:
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中,你会合理地期望:
&#34;开始&#34;
&#34;完成1 https://httpbin.org/delay/1&#34;
&#34;进展1&#34;
&#34;完成0 https://httpbin.org/delay/2&#34;
&#34;进展0&#34;
&#34;全部完成&#34;
但我明白了:
&#34;开始&#34;
&#34;完成1 https://httpbin.org/delay/1&#34;
&#34;进展未定义&#34;
&#34;完成0 https://httpbin.org/delay/2&#34;
&#34;进展0&#34;
&#34;全部完成&#34;
天堂只知道undefined
来自哪里。
现在尝试交换两个网址的顺序 - 我得到:
&#34;开始&#34;
&#34;完成0 https://httpbin.org/delay/1&#34;
&#34;进展0&#34;
&#34;完成1 https://httpbin.org/delay/2&#34;
&#34;进展0&#34;
&#34;全部完成&#34;
仍然不如预期 - 现在你得到了进步0&#34;两次!
恕我直言,这个功能在jQuery 3中被删除并不令人惊讶。答案 1 :(得分:0)
请尝试使用以下代码:
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');
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div>
</div>
&#13;
我们在这里添加了success
ajax
处理程序,我们通过该处理程序调用了deferred.notify()将被调用的progress