Nested AJAX calls are referenced in another Spanish StackOverflow question and the answer suggests using promises
instead of nesting AJAX calls. And from there I have had some doubts.
Note: I'm going to use jQuery notation by removing quite a few parameters and renaming the functions to make it easier to read. It doesn't 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 questions:
- Are structure A and B equivalent? What is the difference between them?
- Is there an advantage to using one over the other?
- Is one of the methods recommended over the other?
The difference lies in the ease of maintenance, and error handling. Debugging is also much easier.
Promises allow you to maintain immutability in your methods, derived from functional programming, while with callbacks it is more imperative.
Another advantage it has is that promises is native to JS, and unlike the Jquery option , it's a standard.
It also prevents you from escaping the callback hell XD
In relation to the structures that you mention in your question, I would modify the promises part a bit so that it is equivalent.
Udacity has a very short free course that explains very simply and quickly promises
This doesn't answer any of your three questions, but as an alternative here is a relatively recent native JavaScript tool
Fetch API
, which may require a polyfill for certain browsers and uses Promises.