Node.js函数返回undefined

我可能有一些与Node.js的asynchronous问题。

rest.js

var Shred = require("shred"); var shred = new Shred(); module.exports = { Request: function (ressource,datacont) { var req = shred.get({ url: 'ip'+ressource, headers: { Accept: 'application/json', }, on: { // You can use response codes as events 200: function(response) { // Shred will automatically JSON-decode response bodies that have a // JSON Content-Type if (datacont === undefined){ return response.content.data; //console.log(response.content.data); } else return response.content.data[datacont]; }, // Any other response means something's wrong response: function(response) { return "Oh no!"; } } }); } } 

other.js

 var rest = require('./rest.js'); console.log(rest.Request('/system')); 

问题是如果我打电话来自other.js的请求,我总是得到'undefined'。 如果我在rest.js中取消注释console.log,则将http请求的正确响应写入控制台。 我认为问题是在请求的实际响应之前返回值。 有谁知道如何解决这个问题?

最好的dom

首先,剥离你的代码是有用的。

 Request: function (ressource, datacont) { var req = shred.get({ // ... on: { // ... } }); } 

你的Request函数永远不会返回任何东西,所以当你调用它和console.log结果时,它总是会打印undefined 。 您的请求处理程序为各种状态代码调用return ,但这些返回是在单个处理函数中,而不是在Request

尽pipe你对节点的asynchronous性是正确的。 你不可能return请求的结果,因为当你的函数返回时,请求仍然在进行。 基本上,当您运行Request ,您正在启动请求,但可以在将来随时完成。 在JavaScript中处理的方式是使用callback函数。

 Request: function (ressource, datacont, callback) { var req = shred.get({ // ... on: { 200: function(response){ callback(null, response); }, response: function(response){ callback(response, null); } } }); } // Called like this: var rest = require('./rest.js'); rest.Request('/system', undefined, function(err, data){ console.log(err, data); }) 

您将第三个parameter passing给Request ,这是请求完成时调用的函数。 可能会失败的callback的标准节点格式是function(err, data){所以在这种情况下,您成功传递null是因为没有错误,并且将response作为数据传递。 如果有任何状态码,那么你可以认为它是一个错误或任何你想要的。