我有一个路由i,为了获得所有需要多次访问API服务器的数据(根据给定的数据)。
现在,我需要向服务器添加第三个访问权限,它变得非常不可读。
下面的代码正在运行,但我觉得我做得不对(承诺?)--无法确定在这种情况下究竟推荐了什么?
代码:(精简以强调重点)
router.get('/', function(req, main_response) {
http.get(FIRST_API_COMMAND, function (res) {
var moment_respose_content = '';
res.on("data", function (chunk) {
moment_respose_content += chunk;
});
res.on('end',function(){
if (res.statusCode < 200 || res.statusCode > 299) {
main_response.send('error in getting moment');
return;
}
var response = JSON.parse(moment_respose_content );
if (response.success)
{
var data = response.data;
//doing something with the data
http.get(SECOND_API_COMMAND, function (res) {
res.on("data", function (chunk) {
comment_respose_content += chunk;
});
res.on('end',function(){
var response = JSON.parse(comment_respose_content);
if (response.success)
{
var comments = response.data;
main_response.render('the page', {data: data});
return;
}
});
}).on('error', function (e) {
console.log("Got error: " + e.message);
main_response.send('Error in getting comments');
});
return;
}
});
}).on('error', function (e) {
console.log("Got error: " + e.message);
main_response.send('Error in getting moment');
});
});发布于 2015-04-19 08:22:41
您可以为每个远程操作编写一个中间件,然后在get处理程序之前对这些中间件进行use,这样get处理程序就可以简单地访问它们的结果。(如果您需要在等待更早的请求完成之前启动后续请求,承诺可能会有所帮助,但这种情况很少见。)
例如,使用express中间件独立地获取每个远程数据:
var request = require('request');
var express = require('express');
var app = express();
var router = express.Router();
/* middleware to fetch moment. will only run for requests that `router` handles. */
router.use(function(req, res, next){
var api_url = 'https://google.com/';
request.get(api_url, function(err, response, body) {
if (err) {
return next(err);
}
req.moment_response = response.headers["date"];
next();
});
});
/* middleware to fetch comment after moment has been fetched */
router.use(function(req, res, next){
var api_url = 'https://www.random.org/integers/?num=1&min=1&max=100&col=1&base=10&format=plain&rnd=new';
request.get(api_url, function(err, response, body){
if (err) {
return next(err);
}
req.comment_response = parseInt(body);
next();
});
});
/* main get handler: expects data to already be loaded */
router.get('/', function(req, res){
res.json({
moment: req.moment_response,
comment: req.comment_response
});
});
/* error handler: will run if any middleware called next() with an argument */
router.use(function(error, req, res, next){
res.status(500);
res.send("Error: " + error.toString());
});
app.use('/endpoint', router);
app.listen(8000);通常,要获取的远程数据基于主请求的某些参数。在这种情况下,您需要使用req.param()而不是App.use()来定义数据加载中间件。
https://stackoverflow.com/questions/29727397
复制相似问题