Tuesday 16 May 2017

how to get value back through callback

I'm new to Node.js from traditional languages and am still having issues with thinking asynchronously.

I got a function that makes a web service call. I need to call this function and retrieve the data from another class.

module.exports.getInfo = function() {

  var req = http.request(options, function(res) {
    var chunks = [];

    res.on("data", function(chunk) {
      chunks.push(chunk);
    });

    res.on("end", function() {
      var body = Buffer.concat(chunks);
      var results = JSON.parse(body.toString());
      res(results);
    });
  });

  req.end();
};

I'm calling this function through another file:

service = require ('service.js');
helper.getInfo(); 
//how do I get the 'results' variable here?

I am wondering how to get the results of the results variable from the calling function.

I'm confused as to the series of nested functions. Is this the call stack as I understand it?

  • GetInfo
  • req
  • res.on 'end'

How would I pass the data from the final function back through?



via john cs

No comments:

Post a Comment