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

Jun*_*ter 2 javascript events callback node.js

我正在开发一个 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;
    }
  });
};
Run Code Online (Sandbox Code Playgroud)

小智 5

假设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
        }
    });
};
Run Code Online (Sandbox Code Playgroud)

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

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

});
Run Code Online (Sandbox Code Playgroud)