why can't we use async:true in loop?

Multi tool use
why can't we use async:true in loop?
I have gone through the question Javascript - AJAX request inside loops. I understood the question and answer.
var totalQuotes = 1;
var url = http://whisperingforest.org/js/getQuote(1).php;
var amount =0;
var sum = 0;
var bookingAmount = 0;
while (counter < 6) {
$.ajax({
url:url,
async: false,
dataType: 'json',
success:function(data) {
jQuery.each(data, function(index, item) {
amount = amount + item.amount;
sum = sum + item.sum;
bookingAmount = bookingAmount + item.bookingAmount;
});
$('.amount').val(amount);
$('.sum').val(sum);
$('.bookingAmount').val(bookingAmount);
}
});
totalQuotes++;
url = "http://whisperingforest.org/js/getQuote(" + totalQuotes + ").php";
counter++;
}
In above code why can't we use async:true
? What will be the problem if we use it?
async:true
1 Answer
1
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
.
async:false
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.
async:true
async
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.
console.log(counter)
while
success
// 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.
success
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).
Note there are simple solutions for managing the order issue. Not clear if that is a concern here or not
– charlietfl
Jul 1 at 15:03
I expanded the answer a bit @charlietfl, but we're probably getting outside the scope of the original question at this point.
– Daniel Beck
Jul 1 at 15:10
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Comments are not for extended discussion; this conversation has been moved to chat.
– Samuel Liew♦
Jul 1 at 23:03