函数返回“未定义”

时间:2019-09-25 12:50:01

标签: javascript

不确定我缺少什么,有人可以解释为什么结果总是不确定的吗?

在下面的代码中,我正在发送一个get请求,我想将结果返回给调用者。

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; 
}

0 个答案:

没有答案