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

node.js/express chaining multiple get commands

我有一条路线,为了获得所有数据需要多次访问 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');
        });
});

您可以为每个远程操作编写一个中间件,然后 useget 处理程序之前编写这些中间件,因此 get 处理程序可以简单地访问它们的结果。 (如果您需要在等待较早的请求完成之前启动后续请求,Promises 会有所帮助,但这种情况很少见。)

例如使用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() instead of App.use() 来定义数据加载中间件。