BaSic BaSic - 4 months ago 8
Javascript Question

Can't get data from for-loop

Another problem... I have 2 functions :

function(data, callback){ //F1
var URL = 'url';
request(URL, function(err, response, body) {
if(response.statusCode == 200){
var json = JSON.parse(body);
var chid = [];
for(var i = 0; i < json['champions'].length;i++){
chid.push(json['champions'][i].id);
}
data.rotation = chid;
free = chid;
callback(null, data);
}

});
},
function(data, callback) { //f2
for (var r=0; r<10; r++){
var URL = 'url';
request(URL,function(err, response, body) {
if(response.statusCode == 200){
var json = JSON.parse(body);

x.push(json.name);
data.rot = x;
}
})
}
callback(null, data);
},


With F1 everything is ok. If I call
console.log(free)
or
console.log(data.rotation)
I got the array I want.

Function 2 is a bit problematic. Data is not avaible outside the for-loop. If I call
console.log(data.rot)
or
console.log(x)
outside the loop, it says it's undefined, so I can't get it with handlebars. I have no idea if it's all about the callback(null, data) position or about the for-loop. I can't handle it alone.


How to get access to data outside of the for-loop, and how to fix this code?

Answer

F2 is async. So to callback you need to wait till the requests returns:

function(data, callback) {        //f2
    for (var r=0, dataRx=0; r<10; r++){
        var URL = 'url';
        request(URL,function(err, response, body) {
            if(response.statusCode == 200){
                var json = JSON.parse(body);

                x.push(json.name);
                data.rot = x;
            }
            dataRx++;
            if(dataRx === 10) callback(null, data);
        })
    }

},