2

var exports = module.exports = {};
var http = require('http');

exports.get = function(key, app, vari) {
    http.get('<url here>/?key='+key+'&app='+app+'&var='+vari+'&req=0', function (response) {
        response.setEncoding('utf8');
        response.on('data', function(body) {
            console.log(body);
            return body;
        });
    });
};

My code (seen above) will output the response to the console just fine, but when trying to use the function in an export, it returns 'undefined' no matter what. The responses it receives are one line and are in the content type of "application/json". What's up with it? (And no, it's not the "url here", I just removed the URL for privacy reasons. If it helps, I can provide it.)

Joshua Herron
  • 85
  • 1
  • 8
  • 2
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – slebetman Dec 28 '16 at 02:51

3 Answers3

0
exports.get = function(key, app, vari) {

return

    http.get('<url here>/?key='+key+'&app='+app+'&var='+vari+'&req=0', function (response) {
        response.setEncoding('utf8');
        response.on('data', function(body) {
            console.log(body);
            return body;
        });
    });
};
Michael Lorton
  • 43,060
  • 26
  • 103
  • 144
0

reference,and you need to listen end event and return a promise instead, just like:

var exports = module.exports = {};
var http = require('http');

exports.get = function(key, app, vari) {
    return new Promise(function(resolve) {
        http.get('<url here>/?     key='+key+'&app='+app+'&var='+vari+'&req=0', function (response) {
      response.setEncoding('utf8');
      var data = '';
      response.on('data', function(chunk) {
          console.log(chunk);
          data += chunk;
      });
      response.on('end', function() {
          resolve(JSON.parse(data));
      });
  });
})

}

Jax2000
  • 1
  • 1
0

I figured it out, I just needed to have a call for an answer.

var exports = module.exports = {};
var http = require('http');

exports.get = function(key, app, vari, answ) {
http.get('http://<url here>/?key='+key+'&app='+app+'&var='+vari+'&req=0', function (response) {
        response.setEncoding('utf8');
        response.on('data', function(body) {
            answ(body);
        });
    });
};
Joshua Herron
  • 85
  • 1
  • 8