Does jquery's getjson method always run after everything else?

Does jquery's getjson method always run after everything else?
0.0 0

#1
var channels = ["ESL_SC2", "OgamingSC2", "cretetion", "freecodecamp", "storbeck", "habathcx", "RobotCaleb", "noobs2ninjas"];

function getChannelInfo() {

    channels.forEach(function(channel) {
            
        console.log("outside");
                
        $.getJSON("https://wind-bow.glitch.me/twitch-api/streams/cretetion?callback=", function(data) {
            console.log("inside");
        });
                
    });
        
};
        
$(document).ready(function() {
    getChannelInfo();
})

In this code, the console.log in the getJSON method does not run until after the forEach loop has ended. I thought that the getJSON method would run simultaneously to everything else.


#2

Nope. You have reached JavaScript enlightenment. It hits us all at some point, but welcome anyway.

Let’s step aside from the code and think conceptually. What does getJSON actually do? It takes sends a request to another web server for data. The other web server will process the data and respond with the data back to you. Unfortunately, requests and responses can’t happen simultaneously. Even the best connections still take time. When you send a request, it could be 400 milliseconds to 4 seconds depending on your connection speed. For loops on the other hand (and similar loops such as while and forEach) are synchronous. You are encountering the wonderful world where asynchronous meets the synchronous. Let me give sort of a loose pseudo-code of what is happening in your case:

channels = [1, 2, 3]

call getChannelInfo()

for every value in channels, do this {
  log('outside')
  requestData(someURL) and when this data responds, log('inside')
}

outside
requestData

outside
requestData

outside
requestData

// a few milliseconds or seconds later

inside
inside
inside

So there you have it. That’s why getJSON won’t work inside for loops. See if you run into any problems, and if you do, try to figure out a new way to do it since you now know that it doesn’t work. If you still need help, please ask again.


#3

Thanks a lot for that explanation! Seeing how the code is running through your example really clears it up for me. :smile: