In my code, I've been working on sending asynchronous HTTP requests using node, and have received responses from the pages in question. I am able to print anywhere in my code, so am sure that the conditions I've made are being met, and the code is functioning.
However, when I call console.log(array)
, []
is returned to me. It appears to me that either this is happening before the other code (i.e. items being added to the array). In a previous version of the code, I was able to print []
, but also included console.log(array.length)
with this print, and could see the size of the array incrementally increasing.
Could anyone offer me a potential fix?
My code is as follows:
var http = require('http');
var most = 25;
var array = [];
function mainfunc(pg) {
if (pg >= most) {
console.log(array);
return;
}
var site = {
host: '[redacted]',
path: '/json?Page=' + pg
};
http.request(site, function(response) {
var stc = []
response.on('data', function (chunk) {
stc.push(chunk);
});
response.on('end', function() {
var no = Buffer.concat(stc).toString();
try {
var no2 = JSON.parse(no)
} catch (e) {
console.log('Error on ' + pg)
}
for (i in no2) {
array.push(no2[i].Id);
};
});
}).end();
};
for (var g = 1; g < 25; g++) {
mainfunc(g);
}