Javascript返回没有返回任何内容

时间:2015-05-28 00:40:08

标签: javascript node.js

我有一个NodeJS服务器和一个正在发出HTTP请求的辅助函数,但是当我调用该函数时,它会显示为未定义。这个电话是在一个回调中进行的,所以我不认为它的异步部分存在问题。

这是server.js

console.log(dictionary('wut'));

这是功能词典。

if(dictionary[word]===undefined){
    request({
        url:"https://mashape-community-urban-dictionary.p.mashape.com/define?term="+word,
        headers:{
            'X-Mashape-Key':'KEY HERE',
            'Accept':'text/plain'
        }
    }, function(err, response, body){
            if(!err && response.statusCode==200){
                var info = JSON.parse(body);
                console.log(info.list[0].definition);
                return info.list[0].definition;
            }
    });
} else {
    return dictionary[word];
}

单词是传递给函数的单词。

编辑:我忘了提到字典功能

module.exports = function(word){

return语句应该为模块提供回调的值。很抱歉,那是一个重要的信息。

2 个答案:

答案 0 :(得分:1)

您将要使用辅助方法使用回调方法。

所以你的助手定义看起来像这样:

function dictionary(word, callback) {
    request({}, function(err, res, body) {
        if (err) {
            return callback(err);
        }

        callback(null, body);
    });
}

你的电话会变成:

dictionary('wut', function(err, result) {
    if (err) {
        return console.error('Something went wrong!');
    }

    console.log(result);
});

这显然是一个非常简单的实现,但概念就在那里。您的助手/模块/应该编写什么来接受回调方法,然后您可以使用这些方法冒出错误并在应用程序的适当位置处理它们。这几乎是在Node中执行操作的标准方法。

以下是使用简单的Express路线呼叫助手的方法:

router.route('/:term')
    .get(function(req, res) {
        dictionary(req.params.term, function(err, result) {
            if (err) {
                return res.status(404).send('Something went wrong!');
            }

            res.send(result);
        });
    });

答案 1 :(得分:0)

从我的观点来看,您使用的request库看起来是异步设计的。这意味着您应该处理回调函数内部的数据。

例如:

function handle(data) {
  // Handle data
  console.log(data)
}

if(dictionary[word]===undefined){
  request({
    url:"https://mashape-community-urban-dictionary.p.mashape.com/define?term="+word,
    headers:{
        'X-Mashape-Key':'KEY HERE',
        'Accept':'text/plain'
    }
  }, function(err, response, body){
    if(!err && response.statusCode==200){
      var info = JSON.parse(body);
      console.log(info.list[0].definition);
      handle(info.list[0].definition)
    }
  });
} else {
  handle( dictionary[word] )
}

您没有为我提供足够的信息来正确设置。但希望这可以让您了解自己需要做什么。

详细说明为什么要以这种方式进行设置:

  1. 请求函数似乎是异步的,因此请保持它的设计方式。
  2. 您正在回调内部返回,因此您的外部dictionary函数没有获得返回的数据,回调是。
  3. 由于request函数设计为异步,因此没有办法将数据返回到dictionary而不强制它同步(不建议这样做)。所以你应该重组它以在回调内处理。
  4. (另一个小注意事项,你应该使用typeof dictionary[word] === "undefined",因为我相信JavaScript有时会抛出错误。)