In another question of StackOverflow in Spanish is done reference to nested AJAX calls and the response suggests using promises
instead of nesting AJAX calls. And from there I have some doubts.
Note: I'm going to use jQuery notation by eliminating enough parameters and renaming the functions to make it easier to read. It does not mean that this question is about jQuery or AJAX in jQuery.
Basically what the question asks is this:
Structure A
$.ajax({
url: URL1,
success: function() {
a1();
$.ajax({
url: URL2,
success: function() {
a2();
},
error: function() {
b2();
}
});
},
error: function() {
b1();
}
});
And what is suggested in the answer is something like this:
Structure B
var promise = $.ajax({
url: URL1,
success: function() {
a1();
},
error: function() {
b1();
}
});
promise.then(function() {
$.ajax({
url: URL2,
success: function() {
a2();
},
error: function() {
b2();
}
});
});
And now my doubts:
- Are structures A and B equivalent? What is the difference between them?
- Is there any advantage to using one over the other?
- Is one of the recommended methods on the other?