while working with the twitch api, i had to use two ajax requests inside a forEach loop. The two ajax requests have their respective callback functions. the following outlines the structure of my program:
twitchStreamers = ["name1","name2",...];
var language, views="", html = "";
//var status;
twitchStreamers.forEach(function(streamer) {
// some code
$.getJSON(streamURL, function(streamData) {
var status;
// some code
if(condition){
status = "some value 1";
} else if(condition) {
status = "some value 2";
} else {
status = "some value 3";
}
$.getJSON(channelURL, function(channelData) {
// some code
// access value of status
}) // end of second ajax request
}) // end of 1st ajax request
} //end of forEach loop
I have some console.log statements in both functions. I was of the impression that both the functions would run simultaneously in each iteration. But examining the console shows that the first getJSON callback function and the second callback function are run separately, (the second is run after the first is run n number of times until completion). Why is that so? And how does the variable status
storing a distinct value in each iteration of the first function convey the correct value in each iteration of the second function?