I have an issue with the below code:
the jQuery.each is speeding on without waiting for the JSON request to finish. As a result, the ‘thisVariationID’ and ‘thisOrderID’ variables are being reset by the latest iteration of a loop before they can be used in the slower getJSON function.
Is there a way to make each iteration of the the .each wait until completion of the getJSON request and callback function before moving on to the next iteration?
$.each($('.checkStatus'), function(){
thisVariationID = $(this).attr('data-id');
thisOrderID = $(this).attr('id');
$.getJSON(jsonURL+'?orderID='+thisOrderID+'&variationID='+thisVariationID+'&callback=?', function(data){
if (data.response = 'success'){
//show the tick. allow the booking to go through
$('#loadingSML'+thisVariationID).hide();
$('#tick'+thisVariationID).show();
}else{
//show the cross. Do not allow the booking to be made
$('#loadingSML'+thisVariationID).hide();
$('#cross'+thisVariationID).hide();
$('#unableToReserveError').slideDown();
//disable the form
$('#OrderForm_OrderForm input').attr('disabled','disabled');
}
})
})
Two things two change for a quick fix:
Use
varbefore your variables to make them local instead of global. That way, you’ll get new variable instances for each of your iterations. Always usevarunless you really intend on polluting the global namespace:Use
==to compare instead of=😉Your code will most likely start working as intended after fixing these issues that you seem to have overlooked. But, if you’re willing to go with a more drastic change, you could also make use of Deferreds.
To execute a bunch of fetches in parallel:
To serialize fetches:
Overkill? Perhaps. But it’s flexible, and sometimes may be worth the syntactic sugar of having code that literally reads “when my fetches are done”.
(Note: The above implementation is an optimistic implementation for illustration purposes only. In a real implementation you should also handle failures.)