处理延迟对象数组 [英] Dealing with Arrays of Deferred Objects
本文介绍了处理延迟对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
自从使用$.Deferred
以来,我已经遇到过几次这种情况:我有一个值列表,每个值都以某种方式产生一个Deferred Object,我想在所有Deferred Objects被解析后执行一个回调.
Since using $.Deferred
I've run into this scenario a couple times: I have a list of values each of which yields a Deferred Object in some way and I want to execute a callback once all of the Deferred Objects are resolved.
一个更具体的例子是这样的:
A more concrete example would be something like this:
var urls = [ 'foo.com', 'bar.com', 'baz.com', 'qux.com' ],
defers = [], defer;
for( var i = 0, j = urls.length; i < j; i++ ){
defer = $.ajax({
url: 'http://' + urls[ i ]
});
defers.push(defer);
}
$.when.apply(window, defers).done(function(){
// Do Something
});
是否有比示例中的代码更优雅的解决方案?
Is there a more elegant solution than the code in my example?
推荐答案
写此示例的一种更优雅的方法是使用数组映射函数(或jQuery的$ .map):
A more elegant way to write this example is with the array map function (or jQuery's $.map):
var urls = [ 'foo.com', 'bar.com', 'baz.com', 'qux.com' ];
var defers = urls.map( function( url) {
return $.ajax({
url: 'http://' + url
});
});
$.when.apply(window, defers).done(function(){
// Do Something
});
您甚至可以滚动自己的"whenDone"和"fetchURL"功能:
You could even roll your own "whenDone" and "fetchURL" functions:
Array.prototype.whenDone = function(callback){
return $.when.apply(window, this).done(callback);
}
function fetchURL(url){
return $.ajax({
url: 'http://' + url
});
}
var urls = [ 'foo.com', 'bar.com', 'baz.com', 'qux.com' ];
urls.map( fetchUrl ).whenDone(function(){
// Do Something
});
这篇关于处理延迟对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文