Javascript Execution Order - How Does It Work?

I am completely lost why Javascript does certain things this way, or maybe I wrote something wrong. But why is the code after $ .getJSON executed before the callback completes?

window.ratingCallback = function(data){

     if(data[0].code == 3){  
         ratingHTML = buildHTML(0);
         console.log('a'+ratingHTML);
         return;
     }

     ratingHTML = buildHTML(data[0].rating);
     console.log('b'+ratingHTML);
     return;
 };

  function buildHTML(pageRating){

     for(counter = 1; counter <= 5; counter++){

         if(counter == pageRating){
                 ratingHTML += '<input name="star1" type="radio" class="star" value="'+counter+'" checked="checked"/>';
         } else {
                 ratingHTML += '<input name="star1" type="radio" class="star" value="'+counter+'"/>';    
         }
     }

     return ratingHTML;
 }


$.getJSON("https://domain.com/"+data+"?jsoncallback=?");

console.log(ratingHTML+"WHY DOES THIS EXECUTE FIRST AND NOT AFTER THE CALLBACK SINCE IT IS PLACED AFTER getJSON????");

      

The reason I want this to be different is because I need the HTML rating to be a global variable.

I understand that the callback is called when the remote server has responded, but can I let the remaining end of the script wait for further execution? Not putting all the code in a callback function or some function?

Many thanks!

Ice

+1


source to share


3 answers


The getJSON () call is asynchronous.

It's even mentioned in docs ( http://docs.jquery.com/Ajax/jQuery.getJSON ):



Note. Be aware that the lines after this function will be executed before the callback.

+7


source


getJSON is an asynchronous method which basically means that when you call it, it immediately returns to the main program thread. Thus, it "does not block". You have to put your console.log in a callback method if you want it to be logged after getJSON completes. Or, if you don't want to follow the callback pattern and want your call to be synchronous, use an ajax call and set the async parameter to false. Be aware, however, this will cause the browser to block or be frozen while it is receiving data.



+4


source


AJAX requests are usually done asynchronously (first A in AJAX). This means that the request will start, then it will continue with the code it was executing without waiting for the request to return.

If you want it to wait, you can set the queries to synchronous, but I'm not sure how to do this in jquery.

+3


source







All Articles