JavaScript返回不返回任何东西

我有一个NodeJS服务器和一个帮助函数,正在发出一个HTTP请求,但是当我调用这个函数的时候,这个函数就没有定义。 这个调用是在callback中进行的,所以我不认为Async部分有问题。

这是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]; } 

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

编辑:我忘了提及字典function

 module.exports = function(word){ 

返回语句应该为模块提供来自callback的值。 对不起,这是重要的信息。

你将要用你的帮助器方法使用callback方法。

所以你的帮手定义如下所示:

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

这显然是一个非常简单的实现,但概念在那里。 你的助手/模块/任何应该被写入接受callback方法,然后你可以用它来鼓吹错误,并在你的应用程序的适当位置处理它们。 这几乎是在Node中做事情的标准方式。

以下是如何使用简单的快速路线呼叫您的助手:

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

从我的angular度来看,你使用的request库看起来是asynchronous的。 这意味着你应该处理callback函数中的数据。

例如:

 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. 请求函数看起来是asynchronous的,所以保持它的devise。
  2. 你正在callback的内部,所以你的外部dictionary函数没有获得返回的数据,callback是。
  3. 由于request函数被devise为asynchronous,所以没有办法将数据返回到dictionary而不强制它是同步的(这是不build议的)。 所以你应该重构它在callback内处理。

(另外一点,你应该使用typeof dictionary[word] === "undefined" ,因为我相信JavaScript有时会抛出一个错误。)