Kushagra Agarwal Kushagra Agarwal - 10 months ago 45
Node.js Question

Multiple queries in a single api

I am trying to write an api in nodejs with two queries in it the data fetched from the queries should be merged and a single json response should be send from the server . I tried the following way but somehow i am getting null value.

app.get('/api/task_details',function(req,res,err){
var sql = "select * from users inner join user_level_task on users.user_id=user_level_task.user_id inner join tasks on tasks.task_id = user_level_task.task_id where task_name = 'game'";
var sql2="select * from tasks where task_name='game'";
var res1 = '',res2='';
db.select(sql,function(err,data){
var res1 =data;
})

db.select(sql2,function(err,data){
var res2 = data;
})

res.end(JSON.stringify(res1+res2));
})

Answer Source

Your code should be like this.

app.get('/api/task_details',function(req,res,err){
    var sql = "select * from users inner join user_level_task on users.user_id=user_level_task.user_id inner join tasks on tasks.task_id = user_level_task.task_id where task_name = 'game'";
    var sql2="select * from tasks where task_name='game'";
    var res1 = {}
    db.select(sql,function(err,data1){
        db.select(sql2,function(err,data2){
        res1.data1= data1;
        res1.data2=data2;
        res.end(JSON.stringify(res1));
    })
    })

})
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download