【发布时间】:2015-04-19 08:24:59
【问题描述】:
通过使用async 模块,我得到了类似的东西,而且效果很好。 但是当我尝试重构代码或使其可重用时,它会在完成 HTTP 请求之前完成执行。 Nodejs 以异步方式做很多事情,所以找到解决方案对我来说有点困难。
到现在为止。
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;
}
【问题讨论】:
标签: javascript node.js asynchronous express