我有一个 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];
}
其中 word 是传递给函数的单词。
编辑:我忘了提到字典功能有
module.exports = function(word){
返回语句应该为模块提供回调中的值。抱歉,这是非常重要的信息。
最佳答案
您将希望在辅助方法中使用回调方法。
所以你的助手定义将如下所示:
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);
});
});
关于Javascript return 不返回任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30495386/