通过使用 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;
}
最佳答案
不是从函数返回值,而是传递回调。
exports.unitedStates = function (req, res) {
// pass callback here
japan(function (value) {
res.send(value);
});
}
function japan(cb) {
//async call here
cb(result);
}
关于javascript - 单独函数中的 HTTP 请求[node.js/expressjs],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28581861/