jQuery Deferreds example

by secretgspot

CSS

ol {
  font: italic 1em Georgia, Times, serif;
  color: #999;
}

ol {
    list-style-type: decimal;
}

ol li {
    margin-left: 20px;
}

li div {
    color: #444;
}

li.end {
    padding-top: 10px;
    color: green;
    list-style-type: none;
    margin: 0;
}

JavaScript

var container = $( "<ol/>" ).appendTo( document.body );


var promises = [];

// constructs the array of promises, and attach
// a done callback to each in the process
$.each("one two three four five".split(" "), function(i, str) { 
    // creates a deferred to be resolved after a
    // period of time, and returns a promise
    promises.push( $.Deferred(function(){
           setTimeout( this.resolve, Math.floor(i*500));  
         }).promise()
           .done(function(){
          container.append('<li><div>' + str + '</div></li>' );
    }) );
} );

// applies the array of promises to $.when
$.when.apply(null, promises)
     .then(function(){
       container.append( '<li class="end">all done!</li>' )
     })
     .fail(function(){
       console.log('oops.something went wrong!'); 
    });