0

I cannot access variable op outside the function. I also declared it outside the function, but still I cannot access it... kindly help me... You can run the code and check. I have two console.logs. But only inside function log works.

I have tried other questions answers, such as declaring the var outside the function. Still it is not working

var http = require('http');
console.log("hi")
var options = {
    host: 'api.usergrid.com',
    path: '/siddharth1/sandbox/restaurants'
};
var op = []; //declaring outside function
var req = http.get(options, function(res) {
    console.log('STATUS: ' + res.statusCode);
    console.log('HEADERS: ' + JSON.stringify(res.headers));

    // Buffer the body entirely for processing as a whole.
    var bodyChunks = [];
    res.on('data', function(chunk) {
        // You can process streamed parts here...
        bodyChunks.push(chunk);
    }).on('end', function() {
        var body = Buffer.concat(bodyChunks);
        console.log('BODY: ' + body);
        // ...and/or process the entire body here.
        var body2 = JSON.parse(body);

        op = body2.entities.map(function(item) {
            return item.name;
        });
        console.log(op); // only this works
    })
});

req.on('error', function(e) {
    console.log('ERROR: ' + e.message);
});


console.log("outside function " + op); //this doesnt work


console.log('Server listening on port 80');
John Seen
  • 701
  • 4
  • 15
  • 31

0 Answers0