获取函数的回调以将值返回到父函数

时间:2012-01-23 00:12:17

标签: javascript events node.js callback

我正在开发一个node.js应用。我要做的是让getBody()函数返回URL的响应体。我写这个的方式显然只返回请求函数而不是请求函数返回的内容。我写这篇文章是为了表明我被困在哪里。

var request = require('request');

var Body = function(url) {
  this.url = url;
};

Body.prototype.getBody = function() {
   return request({url:this.url}, function (error, response, body) {
    if (error || response.statusCode != 200) {
      console.log('Could not fetch the URL', error);
      return undefined;
    } else {
      return body;
    }
  });
};

1 个答案:

答案 0 :(得分:4)

假设request函数是异步,您将无法返回请求的结果。

你可以做的是让getBody函数接收一个在收到响应时调用的回调函数。

Body.prototype.getBody = function (callback) {
    request({
        url: this.url
    }, function (error, response, body) {
        if (error || response.statusCode != 200) {
            console.log('Could not fetch the URL', error);
        } else {
            callback(body); // invoke the callback function, and pass the body
        }
    });
};

所以你要像这样使用它......

var body_inst = new Body('http://example.com/some/path'); // create a Body object

  // invoke the getBody, and pass a callback that will be passed the response
body_inst.getBody(function( body ) {

    console.log(body);  // received the response body

});