Chain AJAX Requests with jQuery Deferred
Posted by: Suprotim Agarwal ,
on 7/5/2014,
in
Category jQuery and ASP.NET
Abstract: Use jQuery Deferred and Promise to chain multiple AJAX Requests and execute them asynchronously.
Imagine a scenario where you have a bunch of functions to execute asynchronously, but each function depends on the result of the previous one. You do not have an idea when each function will complete execution. In such cases, you can write Callbacks.
Callbacks are useful when working with background tasks because you don’t know when they will complete. Here’s a prototype of callbacks in action:
This article is taken from my upcoming The Absolutely Awesome jQuery Cookbook at www.jquerycookbook.com
function A(callback) {
$.ajax({
//...
success: function (result) {
//...
if (callback) callback(result);
}
});
}
And here’s a prototype of callbacks in action:
A(function () {
B(function () {
C()
})
});
However this code style leads to too much nesting and becomes unreadable if there are too many callback functions. Using jQuery, the same functionality can be achieved elegantly without too much nesting. The answer lies in Deferred and Promise. Let’s cook up an example:
We have four functions A(), B(), C() and D() that will execute asynchronously. However function B relies on the result of function A(). Similarly function C relies on the result of function B and so on. The task is to execute these functions one after the other and also make the results of the previous function available in the next one.
Asynchronous requests cannot be guaranteed to finish in the same order that they are sent. However using deferred objects, we can make sure that the callbacks for each async request runs in the required order.
Observe this code:
function A() {
writeMessage("Calling Function A");
return $.ajax({
url: "/scripts/S9/1.json",
type: "GET",
dataType: "json"
});
}
function B(resultFromA) {
writeMessage("In Function B. Result From A = " + resultFromA.data);
return $.ajax({
url: "/scripts/S9/2.json",
type: "GET",
dataType: "json"
});
}
function C(resultFromB) {
writeMessage("In Function C. Result From B = " + resultFromB.data);
return $.ajax({
url: "/scripts/S9/3.json",
type: "GET",
dataType: "json"
});
}
function D(resultFromC) {
writeMessage("In Function D. Result From C = " + resultFromC.data);
}
A().then(B).then(C).then(D);
function writeMessage(msg) {
$("#para").append(msg + "");
}
Observe this important piece of code
A().then(B).then(C).then(D);
From the jQuery Documentation: Callbacks are executed in the order they were added. Since deferred.then returns a Promise, other methods of the Promise object can be chained to this one, including additional .then() methods.
And that’s what we are doing here. Every Ajax method of jQuery already returns a promise. When the Ajax call in function A completes, it resolves the promise. The function B() is then called with the results of the Ajax call as its first argument. When the ajax call in B() completes, it resolves the promise and function C() is called with the results of that call and so on. Here we are just adding return in every function to make this chain work.
By the way, you may have observed that we are repeating settings for multiple AJAX calls in the same script. You can clean up the code further by specifying global settings using $.ajaxSetup. Here’s how:
$.ajaxSetup({
type: 'GET',
dataType: "json",
delay: 1
});
and then each call is reduced to
function A() {
writeMessage("Calling Function A");
return $.ajax({
url: "/scripts/S9/1.json",
});
}
Run the sample and you will get the following output:
Once you’ve got your head wrapped around them, jQuery Deferred can be simple yet powerful. The ability to easily chain methods is beautiful and easy on the eyes!
This article is taken from my upcoming The Absolutely Awesome jQuery Cookbook at www.jquerycookbook.com
This article has been editorially reviewed by Suprotim Agarwal.
C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.
We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).
Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.
Click here to Explore the Table of Contents or Download Sample Chapters!
Was this article worth reading? Share it with fellow developers too. Thanks!
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of
DotNetCurry,
DNC Magazine for Developers,
SQLServerCurry and
DevCurry. He has also authored a couple of books
51 Recipes using jQuery with ASP.NET Controls and
The Absolutely Awesome jQuery CookBook.
Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.
Get in touch with him on Twitter @suprotimagarwal or at LinkedIn