【问题标题】:How to append two results of query in one json in Node.js如何在 Node.js 的一个 json 中附加两个查询结果
【发布时间】:2017-10-28 04:07:01
【问题描述】:

以下是我在 node.js 中的代码,我想知道如何将两个查询结果附加到一个 json 中并发送 json 作为响应。

        router.get("/get-meta", function(req, res, next){

    connection.query("select id, country_name from country", function (error, results) {

        if (error) res.json({"status": "failed", "message": error.message});
        else res.send(JSON.stringify({ results }));
    });
    connection.query("select id, currency from currency", function (error, results2) {

        if (error) res.json({"status": "failed", "message": error.message});
        else res.send(JSON.stringify({ results2 }));
    });
});

【问题讨论】:

    标签: javascript json node.js


    【解决方案1】:

    使用 async.parallel 发送并行请求。async.parallel 的结果将是一个结果数组(这将解决您的问题)

    var async = require('async')
    
    router.get("/get-meta", function(req, res, next){
    
        async.parallel([
            function(callback){
                connection.query("select id, country_name from country", function (error, result1) {
                    callback(error,result1)
                });
            },
            function(callback){
                connection.query("select id, currency from currency", function (error, result2) {
                    callback(error,result2)
                });
            }
    
            ],function(err,results){
                if(err){
                    res.json({"status": "failed", "message": error.message})
                }else{
                    res.send(JSON.stringify(results)); //both result1 and result2 will be in results
                }
            })
    });
    

    【讨论】:

    • 如何在返回响应时为每个结果集指定标题?例如,我正在获取如下数据: [[{"id":1,"country_name":"Pakistan"}],[{"id":1,"currency":"PKR"}]] 到 [country: [ {"id":1,"country_name":"Pakistan"}],货币:[{"id":1,"currency":"PKR"}]]
    • 您不能指定标题,但结果将按顺序排列。因此您可以假设 query1(第一个函数)的结果将在 results[0] 和 query2 将在 results[1] 等等
    • 我们可以在第二个函数中使用来自 result1 的一些数据吗?
    • 这是并行函数,两个函数将一起运行,因此您不能使用来自一个函数的数据。在另一个,但你想要这样的操作,你可以使用async.waterfall(但这会连续运行你的函数)
    【解决方案2】:

    首先,你应该找到一个方法以await 进行两次async 操作来完成,然后concat 结果。看看herehere

    你应该使用concat方法。

    这是一个例子:

    var json1 = [{'name': "doug", 'id':5}];
    var json2 = [{'name': "goud", 'id':1}];
    json1 = json1.concat(json2);
    console.log(json1);

    【讨论】:

    • 感谢您的努力,但您提供的参考链接令人困惑和复杂。不过还是谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-29
    • 1970-01-01
    • 2011-06-04
    • 1970-01-01
    • 2022-10-07
    • 2016-11-07
    相关资源
    最近更新 更多