I make an ajax call with getPropertyId function to get data. I use a callback to get results then I use them. My problem is that the second each loop is launched before the end of the first one even if I put it inside the function. Can I synchronize my code to launch the second loop after the end of the first one ?
Thanks
Plugins.DataHelper.getPropertyId(PropertyID, function(data){
//code using data retrived with getPropertyId function
$.each(list, function(index,value){
//code "A" containing asynchronous calls
});
});
$.each(filtredList, function(index,value){
//code "B"
});
This is the very nature of JavaScript – you should definitely get used to event-based programming to avoid similar problems in the future.
Basically something like that should work:
unless you are making AJAX calls inside “code A”. In this case you are out of luck and should probably change your “code A” to use synchronous calls (generally a bad idea) or rewrite your code to work based on events.
One idea is to determine how many elements you want to process, then call a callback after each item has been processed. This callback should check if all the items have been processed (by incrementing counter and comparing it with number of items that were to be processed – this mechanism is similar to how lock works). When the function determines all the items have been processed, it does some actions (otherwise it does not).