2012-01-23 13 views
2

私はnode.jsアプリケーションを開発しています。私がしようとしているのは、getBody()関数が応答の本文をURLに返すことです。私がこれを書いたやり方は、明らかにリクエスト関数を返すだけで、リクエスト関数が返すものではありません。私は私がどこにいるのかを示すためにそれを書いた。 request機能を仮定親関数に値を返す関数のコールバックを取得する

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

非同期である、あなたはリクエストの結果を返すことはできません。

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:ああ、もう復帰する必要はない。それがうれしかった。 –

関連する問題