node.js / express链接多个get命令

我有一条路线,为了让所有的数据需要多次访问API服务器(根据给出的数据)。

现在我需要添加第三个访问服务器,它变得相当不可读。
下面的代码正在工作,但我有一种感觉,我没有做对(承诺?) – 无法弄清楚究竟是什么build议在这种情况下

代码:(剥离以强调这一点)

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'); }); }); 

您可以为每个远程操作编写一个中间件,然后在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()来定义数据加载中间件。