简体   繁体   English

如何在Node.js中的一个json中附加两个查询结果

[英]How to append two results of query in one json in Node.js

Following is my code of in node.js i would like to know how to append two results of query in one json and send the json in response. 以下是我在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 }));
    });
});

use async.parallel to send parallel requests.the result of async.parallel will be an array of results (which will solve your problem) 使用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
            }
        })
});

First of all, you should find a method to await for two async operation to finished, and then concat the results. 首先,您应该找到一种方法来await两个异步操作完成,然后合并结果。 Have a look here or here 在这里这里看看

You should use concat method. 您应该使用concat方法。

Here is an example: 这是一个例子:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM