2012-01-23 122 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