0

I want to be able to set a variable with a simple var myVar = myFunction(); But myFunction has a callback inside of it and thus cannot return the value. I'm a bit lost on how I would convert this code to be able to return a value from the callback so that I could keep the simple variable definition.

#!/usr/bin/node
"use strict";
var http = require('http');

var myHappyVar = getTheData();
console.log(myHappyVar);

///// Functions /////
function getTheData() {
  var data = '';
  var options = {
    host: 'google.com',
    port: 80,
    method: 'GET'
  }

  http.request(options, function(res) {
    res.on('data', function (chunk) {
       data += chunk;
    });
    res.on('end', function(){
      console.log("DATA: " + data);
      return data;
    });
  }).end();

}
The Digital Ninja
  • 1,090
  • 6
  • 22
  • 36

1 Answers1

3

You can't. AJAX requests are asynchronous, and their callbacks don't run until the request is done. That will be in the future, way after the getTheData() function is done.

You are going to need to restructure your code. You can pass getTheData() a callback to run once the data is ready, but you cannot have it return anything.

function getTheData(callback) {
  var data = '';
  var options = {
    host: 'google.com',
    port: 80,
    method: 'GET'
  }

  http.request(options, function(res) {
    res.on('data', function (chunk) {
       data += chunk;
    });
    res.on('end', function(){
      console.log("DATA: " + data);
      if(typeof callback === 'function'){
        callback(data);
      }
    });
  }).end();

}

Then you can do:

getTheData(function(myHappyVar){
  console.log(myHappyVar);
});
gen_Eric
  • 223,194
  • 41
  • 299
  • 337