async:false
is deprecated, for good reason: it blocks the UI until the request is complete, which is not exactly ideal from a usability perspective. Never use async:false
.
The default, async:true
(or simply omitting the async
line altogether) is what you want. The "problem" with async code that I suspect you're referring to is simply that you have to remember that the code is asynchronous! Many developers new to asynchrony try to treat their asynchronous code as though it's synchronous, and end up attempting to manipulate the results of the XHR calls before they've returned.
As one example of the sort of thing that can trip people up see the console.log(counter)
below: it always shows "6" instead of counting from 0 through 5 as you would expect if the code was synchronous. The reason for this is that the all iterations of the while
loop run before the first asynchronous response returns, so by the time the first success
function runs, the counter has already reached its highest value.
// your JSON source doesn't exist; replacing with this sample just for demo:
var url = "https://cors-anywhere.herokuapp.com/https://jsonfeed.org/feed.json";
var counter = 0;
while (counter < 6) {
$.ajax({
url: url,
dataType: 'json',
success: function(data) {
console.log("AJAX success: ", data.title)
console.log("counter: ", counter); // <-- A common mistake: this will always be 6
}
});
// console.log(data) // <-- another common mistake: trying to use the results of the XHR call before it returns
counter++;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Other potential hazards can include ajax calls returning in the "wrong" order (there's no guarantee that each request will take the same amount of time), or (as in the question you linked to) server errors or poor network conditions causing some of the requests to never return at all.
Methods for handling all of those issues exist, of course, but the most important one is simply to be aware that they are possibilities in the first place, so you don't paint yourself into a corner.
The code in your question does not exhibit the problem shown in my sample here, because you are (correctly) only trying to modify your variables within the success
functions, and (because you're just doing addition) it doesn't matter in what order the calls return.
You could achieve some modest performance gains by batching the XHR calls together and only inserting the results into the DOM once all of them are complete; but for only six iterations it may not be worth the trouble.
TL;DR: your code is fine as is (provided you correct the syntax errors and use a real JSON url as noted in comments above).