【问题标题】:Get a function's callback to return a value to parent function获取函数的回调以将值返回给父函数
【发布时间】:2012-01-23 00:12:16
【问题描述】:

我正在开发一个 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;
    }
  });
};

【问题讨论】:

    标签: javascript events node.js callback


    【解决方案1】:

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

    【讨论】:

    • 有点困惑。我不应该在request()之前去掉return吗?
    • @JungleHunter:哦,是的,不再需要return。很高兴它成功了。
    猜你喜欢
    • 2014-01-10
    • 2018-06-25
    • 2014-05-28
    • 1970-01-01
    • 1970-01-01
    • 2011-11-13
    • 1970-01-01
    • 2019-03-12
    • 1970-01-01
    相关资源
    最近更新 更多