Last active
October 28, 2020 20:53
-
-
Save jeffjohnson9046/3abac534ca9ae69b216e7e2b3cf15b52 to your computer and use it in GitHub Desktop.
A quick example of how to use deferred and promise in jquery
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
// jsfiddle: https://jsfiddle.net/Lkxtryvp/1/ | |
var myAwesomeLoop = function(x) { | |
// This is the magic sauce right here - you're creating a unit of work that will be done at some | |
// point in the future. We're not exactly sure when, but the deferred object will notify us when | |
// it's done (by calling "resolve()" or "reject()" on itself). | |
var deferred = $.Deferred(); | |
// We'll create a simple loop to concatenate some values together. This simulates where the | |
// actual, for-real work would be done (e.g. an AJAX request, some sort of long-running calculation, etc) | |
var result = "" | |
for (var i = 0; i < x; i++) { | |
result += i; | |
} | |
// Let's take a quick look at what this loop produced: | |
console.log("the output of myAwesomeLoop: %s", result); | |
// When myAwesomeLoop is done doing its work, we call "resolve()" on the deferred object to say | |
// we're done and everything worked properly. If we had some sort of error, we could call | |
// "reject()" and bubble up an error. Note that "resolve()" takes in an argument - that's data that can be returned | |
// by the promise. | |
deferred.resolve(result); | |
// The deferred object has a promise in it, which is what we want to return. We can then chain | |
// other methods off this one that won't get called until this one completes. We want to return the promise because | |
// promises are immutable. | |
return deferred.promise(); | |
} | |
// Let's use the when(), then() and done() methods provided by jQuery to chain off our myAwesomeLoop promise. If we wanted to | |
// handle an error/exception condition, we could add a call to "fail()". If we have an operation that we want to occur | |
// regardless of success or failure, we could add a call to "always()". | |
myAwesomeLoop(5) | |
.then(function(data) { | |
var deferred = $.Deferred(); | |
console.log("If I needed to do something else, I can use then() to continue the chain of execution. I can also get data passed into it. Here's what came from the 'when()' call: %s", data); | |
deferred.resolve(); | |
return deferred.promise(); | |
}) | |
.done(console.log("No more chain to execute I'm done!")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment