2012-01-23 120 views
2

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

回答

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 

}); 
+0

有点儿困惑。我不应该在request()之前摆脱'return'吗? –

+0

编辑你的答案。有用!你摇滚! –

+0

@JungleHunter:哦,是的,不需要'返回'了。很高兴它的工作。 – 2012-01-23 01:52:15