Last active
December 26, 2015 12:39
-
-
Save alch/7152671 to your computer and use it in GitHub Desktop.
JQuery Promise example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
<!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> | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment