JQuery Deferred: $ .when () with multiple objects

I need a method to retrieve different scripts with a callback. This method works fine:

fetchScripts:function() { var _this=this; $.when( $.ajax({ url:_this.url + 'library/script-one.js', type:'get', cache:true }), $.ajax({ url:_this.url + 'library/script-two.js', type:'get', cache:true }), { .... }, $.ajax({ url:_this.url + 'library/script-n.js', type:'get', cache:true }) ).then(function() { console.log('fetch is done'); }) }, 

But I would like to generalize the method more because redundany is increasing. Is it possible to convey the promise of $ .when ()? Below my first attempt - but the url is always the same, that is, script -n.js' Maybe I missed this point and you could illustrate a more "colorful" solution.

 fetchScripts:function() { this.deferred=new $.Deferred(); this.promise=this.deferred.promise(); var _this=this; $.each([ 'script-one.js', 'script-two.js', ( .... ), 'script-n.js' ],function() { _this.script=this; _this.promise.then(function(){ return $.ajax({ url:_this.url + 'library/' + _this.script, type:'get', cache:true }) }); }); $.when( this.promise ).then(function() { console.log('fetch is done'); }); this.deferred.resolve(); }, 
+7
jquery promise deferred
source share
2 answers

You still need $. But instead, create a deferred array (or promises), and then apply it to $ .when:

 fetchScripts:function() { var base = this.url; var defaults = { type:'get', cache:true }; var libraries = [ 'library/script-one.js', 'library/script-two.js', 'library/script-n.js' ]; var deferreds = $.map(libraries, function(current) { var ajaxOptions = $.extend({ url: base + current }, defaults); return $.ajax(ajaxOptions); }); $.when.apply($, deferreds).then(function() { console.log('All done'); }); } 

Alternatively, to extend the default settings, you can simply use $. ajax (default) .

+27
source share

Try

 fetchScripts: function() { var deferred = new $.Deferred(); var _this=this; var promises = $.map([ 'script-one.js', 'script-two.js', ( .... ), 'script-n.js' ], function(item, idx) { return $.ajax({ url:_this.url + 'library/' + item.script, type:'get', cache:true }) }); $.when.apply($, promises).then(function() { console.log('fetch is done'); deferred.resolve() }); return deferred.promise(); } 
+4
source share

All Articles