Skip to content

Instantly share code, notes, and snippets.

@styfle
Created November 21, 2014 18:41
Show Gist options
  • Save styfle/2ee8dff366e1d930de49 to your computer and use it in GitHub Desktop.
Save styfle/2ee8dff366e1d930de49 to your computer and use it in GitHub Desktop.
var promiseArray = [];
function foo(i) {
var def = $.Deferred();
// This line represents some async code: ajax, setTimeout, etc
setTimeout(function() {def.resolve(i); }, i);
// Return the promise which may not be resolved yet
return def.promise();
}
// Push several promises (typically this is a loop of N items)
promiseArray.push(foo(200));
promiseArray.push(foo(700));
promiseArray.push(foo(20));
// $.when() takes promise arguments and fires done when all promises are done
// Using func.apply() allows us to pass an array of N promises!
$.when.apply($, promiseArray).done(function (data) {
// The first argument is the first return value is the
console.log(data); // prints 200
// Using the magic `arguments` variable, we can get all returned values!
console.log(arguments); // prints [200,700,20]
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment