In jQuery, Deferred objects and Promises are powerful tools used for handling asynchronous operations. They allow you to execute code when certain tasks are completed, providing a more manageable and cleaner approach compared to traditional callbacks. This chapter will guide you through the basics of Deferreds and Promises, how to chain them, and provide detailed examples to help you master these concepts.
Deferred Object: A Deferred object is a mechanism in jQuery for handling asynchronous operations. It provides a way to set up callbacks that will be executed when the operation completes, either successfully or with an error.
Promise Object: A Promise object is a simplified version of a Deferred object. It represents the future result of an asynchronous operation and provides methods to register callbacks for when the operation succeeds or fails.
In jQuery, you can create a Deferred object using the $.Deferred()
function.
var deferred = $.Deferred();
You can obtain a Promise object from a Deferred object using the .promise()
method.
var promise = deferred.promise();
Deferred objects allow you to define callbacks for success, failure, and progress.
deferred.done(function(result) {
console.log("Success: " + result);
}).fail(function(error) {
console.log("Error: " + error);
}).progress(function(progress) {
console.log("Progress: " + progress);
});
.done()
: Registers a callback to be executed when the Deferred is resolved (i.e., the asynchronous operation is successful)..fail()
: Registers a callback to be executed when the Deferred is rejected (i.e., the asynchronous operation fails)..progress()
: Registers a callback to be executed to handle progress updates.You can manually resolve or reject a Deferred object:
deferred.resolve("Operation completed successfully!");
// or
deferred.reject("Something went wrong!");
.then()
The .then()
method returns a new promise resolved with the return value of the called function or with its original settled value if the promise was not handled (i.e., if the callback function throws an error).
deferred.promise().then(function(result) {
console.log("First handler: " + result);
return "Next step";
}).then(function(nextResult) {
console.log("Second handler: " + nextResult);
});
.then()
logs the result of the Deferred."Next step"
which is handled by the next .then()
.
First handler: Operation completed successfully!
Second handler: Next step
.fail()
If an error occurs, you can chain .fail()
to handle it:
deferred.promise().then(function(result) {
console.log("Success: " + result);
return "Proceed";
}).fail(function(error) {
console.log("Caught an error: " + error);
}).then(function(nextResult) {
console.log("Continued with: " + nextResult);
});
.fail()
will handle the error, but the chain will continue if you return a value.
Caught an error: Something went wrong!
Continued with: undefined
You can manage multiple asynchronous operations in parallel using $.when()
.
var d1 = $.Deferred();
var d2 = $.Deferred();
$.when(d1, d2).done(function(result1, result2) {
console.log("Both operations completed");
console.log("Result 1: " + result1);
console.log("Result 2: " + result2);
});
d1.resolve("First operation done");
d2.resolve("Second operation done");
$.when()
waits for both Deferreds (d1
and d2
) to complete..done()
handler is executed when both are resolved.
Both operations completed
Result 1: First operation done
Result 2: Second operation done
You can also track progress:
You can obtain a Promise object from a Deferred object using the .promise()
method.
var deferred = $.Deferred();
deferred.progress(function(progress) {
console.log("Progress: " + progress + "%");
}).done(function(result) {
console.log("Done with result: " + result);
});
deferred.notify(50); // Report 50% progress
deferred.resolve("Operation completed!");
Progress: 50%
Done with result: Operation completed!
Let’s put everything together in a real-world scenario:
function asyncOperation1() {
var deferred = $.Deferred();
setTimeout(function() {
deferred.resolve("Result from asyncOperation1");
}, 1000);
return deferred.promise();
}
function asyncOperation2() {
var deferred = $.Deferred();
setTimeout(function() {
deferred.resolve("Result from asyncOperation2");
}, 500);
return deferred.promise();
}
$.when(asyncOperation1(), asyncOperation2())
.done(function(result1, result2) {
console.log("Operation 1 completed: " + result1);
console.log("Operation 2 completed: " + result2);
})
.fail(function(error) {
console.log("An error occurred: " + error);
});
$.when()
waits for both operations to complete..done()
callback handles their results.
Operation 2 completed: Result from asyncOperation2
Operation 1 completed: Result from asyncOperation1
Deferreds and Promises in jQuery provide powerful mechanisms for managing asynchronous operations. By chaining .then(), .fail(), and .progress() methods, you can handle various states of asynchronous tasks effectively. Using $.when(), you can coordinate multiple asynchronous operations and handle their results collectively.This chapter has covered the fundamentals of Deferreds and Promises, their methods, and practical examples to give you a comprehensive understanding. Happy coding !❤️