1

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);
}
GregW
  • 173
  • 6
  • Try to log your data inside the response callback function. – Sotiris Kiritsis Mar 28 '16 at 13:09
  • 4
    Why can't you add the code? There's nothing confidential in there. – Andy Mar 28 '16 at 13:09
  • You are currently trying to log the array content while you still have no content, as said in the first comment, log its content " response.on('end')" callback function – Sami Triki Mar 28 '16 at 13:11
  • @Andy Mainly, the guy who helped me with it is (sadly) reluctant for me to put it on here, but agreed I could put it on pastebin on a timer. Not sure why, sorry. – GregW Mar 28 '16 at 13:17
  • @user340764 Thank you - this works for me. – GregW Mar 28 '16 at 13:18
  • Sorry, but that's going to be no good to people visiting this page in the future who will have no idea what this question is about, and makes the question useless. Please add the code. – Andy Mar 28 '16 at 13:19
  • @GregW Code must be posted here, otherwise the pastebin will no longer be available later on and the question will be totally useless. – Rahil Wazir Mar 28 '16 at 13:20
  • 2
    Sorry, I wasn't aware of that. For the reasons mentioned by both of you, I've decided to add the code. The fix by @user340764 worked for me. – GregW Mar 28 '16 at 13:26

0 Answers0