Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

synchronizing code

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"
});
like image 712
Djoz Avatar asked Dec 01 '25 17:12

Djoz


2 Answers

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:

Plugins.DataHelper.getPropertyId(PropertyID, function(data){
    //code using data retrived with getPropertyId function

    $.each(list, function(index,value){
        //code "A"
    });
    $.each(filtredList, function(index,value){
        //code "B"
    });
});

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).

like image 196
Tadeck Avatar answered Dec 03 '25 06:12

Tadeck


You really could create a syncronised (=blocking) request, but that is pretty bad browser behavior. Much better is to make callback functions work for you, so you need to "continue" the code when that first ajax call is finished( success/error ).

Plugins.DataHelper.getPropertyId(PropertyID, function(data){
    XHRobject.onreadystatechange = function() {
        if( XHRobject.readyState === 4 ) {
            $.each(list, function(index,value){
               //code "A"
            });
        }
    }
});

Note, that is a simplified example to demonstrate the principle. Since you tagged jQuery too, you can make this very georgous by invoking promise objects. Looks like

Plugins.DataHelper.getPropertyId(PropertyID, function(data){
    $.ajax({}).done(function() {
        $.each(list, function(index,value){
           //code "A"
        });
    });
});
like image 23
jAndy Avatar answered Dec 03 '25 05:12

jAndy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!