Home >Web Front-end >JS Tutorial >How to Chain Multiple Asynchronous Calls using jQuery Promises?
In asynchronous programming, it's common to make multiple calls to an API or a server in succession. To handle these calls efficiently, it's desirable to chain them together, ensuring that each call is completed before the next one is executed. With jQuery promises, this chaining process can be accomplished with ease.
Consider the following scenario, where three HTTP calls need to be made in sequence, and data needs to be passed from one call to the other:
<code class="javascript">function first() { ajax(); } function second() { ajax(); } function third() { ajax(); } function main() { first().then(second).then(third); }</code>
In this example, the intention is to make a first call, wait for it to finish, then make a second call using the result of the first call, and finally make a third call using the result of the second call. However, this code won't work as expected. To correctly chain these calls, proper use of jQuery promises is necessary.
<code class="javascript">function first() { var deferred = $.Deferred(); $.ajax({ "success": function(resp) { deferred.resolve(resp); }, }); return deferred.promise(); } function second(foo) { $.ajax({ "success": function(resp) { // do something with the resp }, "error": function(resp) { // handle the error }, }); } first().then(function(foo) { second(foo); });</code>
This code provides a partial solution, but chaining for three functions is still not achieved. The key to chaining multiple calls lies in returning the jqXHR object returned by $.ajax() in each function. These objects are Promise-compatible and can be chained using .then()/.done()/.fail()/.always().
<code class="javascript">function first() { return $.ajax(...); } function second(data, textStatus, jqXHR) { return $.ajax(...); } function third(data, textStatus, jqXHR) { return $.ajax(...); } function main() { first().then(second).then(third); }</code>
In this revised code, the jqXHR object returned by each $.ajax() call represents the Promise of the respective function. This allows the functions to be chained sequentially, with the output of one function being passed as input to the next.
The arguments data, textStatus, and jqXHR arise from the $.ajax() call in the previous function. For instance, first() feeds second(), and second() feeds third(), passing along any relevant data.
To see this chaining in action, a live demonstration using $.when('foo') to deliver a fulfilled promise is provided below.
The above is the detailed content of How to Chain Multiple Asynchronous Calls using jQuery Promises?. For more information, please follow other related articles on the PHP Chinese website!