John Seen John Seen - 5 months ago 7
Node.js Question

how to use nodejs async module?

This is a different question and I am unable to get a solution for this, please do not mark it duplicate.

I cannot access variable op outside the function. Should I be using a async module of nodjes?
I have two console.logs. But only inside function log works.

I have tried other questions answers. 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) {

// 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);

// ...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');

Answer

Node.js instantiates the variable op as an empty array:

var op = []; //declaring outside function

It then calls the .get() function of the http module, and passes it options and a callback function.

var req = http.get(options, function(res) {
  ...
});

The code inside the callback function is not executed until an HTTP GET request is received by your application.

Node then continues, and executes the remainder of your code:

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

The above line is executed and indeed, op is an empty array as you defined it to be an empty array - and nothing has yet modified 'op'.

The server then idles, waiting for any incoming HTTP requests.

Much later, you of course issue a HTTP GET request to your server. The callback function you registered gets called, and the code inside that function executes.

If I were you I would look into some fundamental tutorials on Node.js, specifically looking into it's non-blocking model. Good luck.

Note: Ryan Dahl's original node.js presentation is a rather long video and a little old, but perfectly explains the way Node.js works, and I highly recommend you give it a watch.

Comments