Playing with Defers
Defers
by Fernando De Leon
HTML
<button id="b1">
Press to start
</button>
<div id="here">
</div>
<div id="status">
</div>
<div id="whenDone">
</div>
JavaScript
function asyncEvent() {
var dfd = jQuery.Deferred();
// Resolve after a random interval
setTimeout(function() {
dfd.resolve( "hurray" );
}, Math.floor( 400 + Math.random() * 2000 ) );
// Reject after a random interval
setTimeout(function() {
dfd.reject( "sorry" );
}, Math.floor( 400 + Math.random() * 2000 ) );
// Show a "working..." message every half-second
setTimeout(function working() {
if ( dfd.state() === "pending" ) {
dfd.notify( "working... " );
setTimeout( working, 500 );
}
}, 1 );
// Return the Promise so caller can't change the Deferred
return dfd.promise();
}
$("#b1").on("click",function() {
$("#status").html("");
$("#here").html("");
$("#whenDone").html("");
// Attach a done, fail, and progress handler for the asyncEvent
$.when( asyncEvent() ).then(
function( status ) {
//alert( status + ", things are going well" );
$("#status").append(status + " WON ");
},
function( status ) {
$("#status").append(status+" WON ");
},
function( status ) {
$( "#here" ).append( status );
}
);
$.when(asyncEvent()).done(function(status) {
$("#whenDone").append("<h3 style='color:blue;'>"+status+"</h3><br/>");
});
$.when(asyncEvent()).fail(function(status) {
$("#whenDone").append("<h3 style='color:red;'>"+status+"</h3><br/>");
});
$.when(asyncEvent()).always(function(status) {
$("#whenDone").append("<h3>"+status+"</h3><br/>");
});
});
// Attach a done, fail, and progress handler for the asyncEvent