I am developing an application that uses the twitch API and in the process makes two AJAX requests, one inside another. A simplified version of my code:
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
Notice the status
variable.
This design works perfectly with what i want to do i.e. when i access the status variable inside the second ajax request, it has the correct value of status
with respect to the current loop iteration. But when i declare the variable status
outside forEach loop it always has the value some value 3
(initialised in the else part of the conditionals) when accessed in the second AJAX request. Why is this so?
Note that the variable status
is always initialised correctly in the first AJAX request irrespective of where the variable is declared.