Node.js函数返回undefined

时间:2013-02-15 13:20:51

标签: node.js

我可能在Node.js的异步性方面存在一些问题。

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

问题是,如果我从其他人那里调用请求。我总是得到'未定义'。如果我取消注释rest.js中的console.log,那么http请求的正确响应将写入控制台。我认为问题是在请求的实际响应存在之前返回值。有谁知道如何解决这个问题?

最佳, DOM

1 个答案:

答案 0 :(得分:4)

首先,删除你拥有的代码非常有用。

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

您的Request函数根本不会返回任何内容,因此当您调用它并console.log结果时,它将始终打印undefined。您的各种状态代码的请求处理程序调用{​​{1}},但这些返回位于各个处理程序函数内部,而不在return内。

你对Node的异步性质是正确的。你不可能Request请求的结果,因为当你的函数返回时,请求仍然在进行中。基本上,当您运行return时,您正在启动请求,但它可以在将来的任何时间完成。在JavaScript中处理它的方式是使用回调函数。

Request

您将第三个参数传递给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); }) ,这是一个在请求完成时调用的函数。可能失败的回调的标准节点格式为Request,因此在成功的情况下,您传递function(err, data){因为没有错误,并且您将null作为数据传递。如果有任何状态代码,那么您可以将其视为错误或任何您想要的。