Reputation: 125
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.
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 }));
});
});
Upvotes: 0
Views: 2567
Reputation: 356
use async.parallel to send parallel requests.the result of async.parallel will be an array of results (which will solve your problem)
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
}
})
});
Upvotes: 3
Reputation: 48367
First of all, you should find a method to await
for two async operation to finished, and then concat the results. Have a look here or here
You should use concat
method.
Here is an example:
var json1 = [{'name': "doug", 'id':5}];
var json2 = [{'name': "goud", 'id':1}];
json1 = json1.concat(json2);
console.log(json1);
Upvotes: 1