1

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));
})

2 Answers 2

1

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));
    })
    })

})
Sign up to request clarification or add additional context in comments.

Comments

0

Try this piece of code

const mysql = require('mysql');
const express = require('express');
const app = express();
var async = require('async');
const connection = mysql.createConnection({
    host: 'localhost',
    user: 'xxxx',
    password: 'xxxx',
    database: 'Name of the DataBase'
});

connection.connect();
app.get('/api/task_details', (req, res) => {
async.parallel([
function (callback)
{ 
setTimeout(function(){
connection.query(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', (error, data1) => {
        if(error) => {
            console.log(error)
       } 
        callback(null,data1);
    });
   },200);
}

function (callback)
{ 
setTimeout(function(){
connection.query(SELECT * FROM tasks where task_name='game',(error, data2) => {
        if(error) => {
            console.log(error)
        }
        callback(null,data2);
    });
},100);
    }
    ],
    function(err,results){
        res.end(JSON.stringify(results));
    });

});

Hope this helps for you

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.