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:
function first() {
ajax();
}
function second() {
ajax();
}
function third() {
ajax();
}
function main() {
first().then(second).then(third);
}
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.
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);
});
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().
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);
}
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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3