Skip to content

Instantly share code, notes, and snippets.

@restlessmedia
Last active August 29, 2015 14:01
Show Gist options
  • Save restlessmedia/36dcf9161356b805d796 to your computer and use it in GitHub Desktop.
Save restlessmedia/36dcf9161356b805d796 to your computer and use it in GitHub Desktop.
Multiple template fetching with promises
var getTemplate = function(url){
var deferred = $.Deferred();
// simulate latency
setTimeout(function(){
deferred.resolve('template-result-done-'+url);
}, 1000);
return deferred.promise();
}
var fetch = function(/* params string[] urls */){
var length = arguments.length;
var deferred = $.Deferred();
if(length){
var i = 0;
var promises = [];
while(i < length){
promises.push(getTemplate(arguments[i]))
i++;
}
$.when.apply($, promises).done(function(){
deferred.resolve(arguments);
});
}else{
deferred.resolve();
}
return deferred.promise();
}
fetch('thisTemplate','thatTemplate').done(function(tmpl1, tmpl2){
console.log(tmpl1, tmpl2)
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment