单独函数中的HTTP请求

通过使用asynchronous模块,我有这样的东西,它完美的作品。 但是当我尝试重构代码或使其可重用时,它在完成HTTP请求之前完成执行。 Nodejs以asynchronous方式做很多事情,所以find解决scheme对我来说有点难。

我到现在为止。

var async = require('async'), http = require('http'); exports.unitedStates = function(req, res) { var texas = { //GET method data here / ex: host, path, headers.... }; var washington = { //GET method data here / ex: host, path, headers.... }; async.parallel({ getSource: function(callback) { http.request(texas, function(respond) { //Http request }).end(); }, getScreen: function(callback) { http.request(washington, function(respond) { //Http request }).end(); } }, function(err, results) { //Return the results /* REPLY TO THE REQUEST */ res.send( /* data here */ ); }); } 

有没有一种完美的方式来使这段代码可重用

 exports.unitedStates = function(req, res) { var tokyo = japan(); //send the result to front end res.send(tokyo); } function japan(){ //async calls comes here and return the value... return result; } 

而不是从函数返回值,传递一个callback。

 exports.unitedStates = function (req, res) { // pass callback here japan(function (value) { res.send(value); }); } function japan(cb) { //async call here cb(result); }