JQuery Promise example
/*
<!doctype html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<script>
*/
/**
* JQuery $.Deferred example
*/
(function(){
function asyncEvent() {
var dfd = new jQuery.Deferred();
// the Deferred will be resolved asynchronously in 3 secs
setTimeout(
function() {
dfd.resolve("RESOLVED");
} ,
3000);
// Return the Promise
// The promise object is used expressly not to mangle with
// the Deferred object status.
// the Promise will only expose callbacks to attach events
// but the resolution or the rejection of the Deferred must
// be done from the Deferred instance (thus we have to access
// the "dfd" instance somewhere in order to
// call .resolve(), .reject(), .progress())
return dfd.promise();
}
// Attach a done, fail, and progress handler to the Deferred
//
// We can do this in various whay in JQuery:
// 1) using the Deferred .done(), .fail() methods
// 2) using the Promise .done(), .fail() methods
// 3) using $.when(Dferred|Promise) .done(), .fail() method
//
// the .then() method is where we can cascade actions based on
// the succesfull resolution of the Deferred
asyncEvent().done(
function(status) {
console.log(status + " done!");
}
).fail(
function(status) {
console.log(status + " failed");
}
).progress(function() {
console.log("Async still running...")
}
).then(function() {
console.log("doing some other thing...");
});
console.log("this is my normal flow...");
})();
/*
</script>
</body>
*/