1

I am trying getting data from an api but the For-loop that i was using was returning objects with null and undefined values in the nested GetJSON call but when i tried forEach loop it works fine. Any ideas why?

var baseUrl = "https://wind-bow.gomix.me/twitch-api/";
var channels = ["ESL_SC2", "FreeCodeCamp", "Test_channel", "brunofin"];

//**First function with forEach. WORKS FINE**
function getDataForEach() {

    channels.forEach(function(channel) {

        $.getJSON(txtUrl('streams', channel), function(json) {
            console.log(json);

            $.getJSON(txtUrl('channels', channel), function(json2) {
                console.log(json2);

            });
        });

    });
}

//**Second function with a normal for loop. The 2nd JSON doesnt return the proper data**

function getDataForLoop() {
        for (i=0;i<channels.length;i++){
            $.getJSON(txtUrl('streams', channels[i]), function(json) {
                console.log(json);

                //THIS 2nd call doesnt returns undefined objects. 
                $.getJSON(txtUrl('channels', channels[i]), function(json2) {
                    console.log(json2);

                });
            });

        });
    }

function txtUrl(prop, chnl) {
    return baseUrl + prop + '/' + chnl + '?callback=?';
}

$(document).ready(function() {
            getData();
});
A.DDu
  • 13
  • 2

2 Answers2

3

getJSON is asynchronous, so its callback function won't be executed right away, thus in the case of for loop it will produce this error if you use i inside the callbacks.

Another thing I've noticed is that you use a global i which is also a source of troubles.

If you'are using ECMAScript 6 you can use let to declare i:

for(let i = 0; ...)

let is block-scoped so using it won't produce the error in the first link above.

ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73
0

I think it has to do with the fact that forEach is a callback function and for is not. So for is executing before data is received.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

Patricia Green
  • 495
  • 5
  • 14