0

I am trying to understand why the getSalaries variable is logging undefined to the console. The call to the web service is fine and if I replace my return statement in dataResult function with console.log(result); the JSON prints ok. Here is the code:

var http = require('http');

var options = {
  host: 'redacted',
  port: '80',
  path: '/redacted',
  method: 'GET',
  headers: {
    'Content-Type': 'application/json; charset=utf-8'
  }
};


var getSalaries = function(callback){

  var salaries = getMFLData(options, dataResult);
  callback(salaries);

}

var processSalaries = function(salaries){
  console.log(salaries);
}

getSalaries(processSalaries);

function getMFLData(options, callback){
  http.request(options, function(res){
    var body = '';

    res.on('data', function(chunk){
      body+= chunk;
    });

    res.on('end', function(){
      var result = JSON.parse(body);
      callback(null, result);
    });

    res.on('error', callback);

  })
  .on('error', callback)
  .end();
}

function dataResult(err, result){
  if(err){
    return console.log('an error occured getting MFL data ', err);
  }
  return result;
};

Thanks for any help on this one. I am simply trying to reuse the getMFL function for multiple calls but cannot figure out how to get the return value.

Dave

braucktoon
  • 21
  • 2
  • `salaries` is undefined in `var salaries = callback(salaries);` – Phil Oct 10 '17 at 00:12
  • Most of the time when something is undefined after an ajax-request you didn't account for the async nature correctly. Try reading up on the topics async/await and the new fetch api. – xDreamCoding Oct 10 '17 at 00:15
  • Most of the code you've posted is never used. You're really only using `getSalaries` and `processSalaries`. When you call `callback(salaries)` in `getSalaries`, `salaries` is undefined so I'm not sure why you'd expect `processSalaries` to log anything other than that – Phil Oct 10 '17 at 00:21
  • whoops, I had some old code there, I updated the getSalaries function to actual do something. – braucktoon Oct 10 '17 at 00:26
  • 1
    `getFMLData()` doesn't return anything. – Barmar Oct 10 '17 at 00:27
  • Barmar, you are correct, I callback to dataResult and return from there, is that not allowed? How can I get the JSON from this function? – braucktoon Oct 10 '17 at 00:29

0 Answers0