Skip to content

Instantly share code, notes, and snippets.

@cowboy
Created August 20, 2012 01:37
Show Gist options
  • Save cowboy/3399155 to your computer and use it in GitHub Desktop.
Save cowboy/3399155 to your computer and use it in GitHub Desktop.
jQuery .when example (I don't think I need it)
// Using the $.when() method, we can create an object that behaves similarly
// to Deferred objects, but for COMBINATIONS of Deferred objects.
//
// The $.when() method creates a Deferred object that is resolved or rejected
// when all the Deferred objects passed into it are resolved or rejected.
var getPromise = function(name) {
var dfd = $.Deferred();
var num = Math.floor(Math.random() * 1000);
setTimeout(function() { dfd.resolve(name + ": " + num); }, num);
return dfd.promise();
};
var list = $("<ul/>").appendTo($("#target").empty());
var printLine = function(str) {
$("<li class=well/>").html(str).appendTo(list);
};
// Each of these Promises will individually print when resolved.
var promiseA = getPromise("A").done(printLine);
var promiseB = getPromise("B").done(printLine);
var promiseC = getPromise("C").done(printLine);
// And this code will execute once all Promises have resolved.
$.when(promiseA, promiseB, promiseC).then(function(numA, numB, numC) {
printLine(numA + ", " + numB + ", " + numC);
});
@michaelmior
Copy link

I use .when a lot for single Deferreds, but when I'm not sure whether the object will actually be a Deferred. For example, if I have a piece of data that may or may not have been fetched already. Instead of having two different code paths, I simply assign a variable to the existing piece of data or to the return value of $.ajax. Then $.when(var).then(function(data) { ... }); behaves as expected in both scenarios.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment