0

Not sure what am I missing, can someone please explain why the result is always undefined?

In the code below I'm sending a get request and I want to return the results back to the caller.

var output = getUserName('the input');
console.log(output) // undefined <------

function getUserName(userInput) {
    var result = '';
    const https = require('https');
    var token = 'xoxp-fdfs-fdsf';
    var user = userInput.split(" ");
    var url = 'https://slack.com/api/users.info?token=' + token +'&user=' + user;

    https.get(url, (resp) => {
      let data = '';

      // A chunk of data has been recieved.
      resp.on('data', (chunk) => {
        data += chunk;
      });

      // The whole response has been received. Print out the result.
      resp.on('end', () => {

        data = JSON.parse(data);
        console.log('data.user.name: '+data.user.name); //output: John Doe (as expected)
        result = data.user.name;
        return result;

      });

    }).on("error", (err) => {
      console.log("Error: " + err.message);
      return "Error: " + err.message;
    });   

    return result; 
}
Json
  • 655
  • 10
  • 27
  • 1
    It's an async call, so you return `result` but that hasn't yet been populated by `result = data.user.name`. Also, you should not be getting `undefined` but an empty string, since the value you have at the time of the function execution is `var result = ''` – VLAZ Sep 25 '19 at 12:52
  • Can't return value from an async call. – Rohit Kashyap Sep 25 '19 at 12:52

0 Answers0