单独函数中的 HTTP 请求[node.js/expressjs]
HTTP request in separate function[node.js/expressjs]
通过使用 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);
}
通过使用 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);
}