CHALLENGER
CHALLENGER

Reputation: 1

Return value from a function

I'm trying to return value from a function getdata, but it doesn't work.

Code

app.post('/home.html',function(req,res){
   //console.log(req.body);
   con.query('SELECT MAX(user_id) as id FROM users',(err,rows)=> {
        if(err) throw err;
        console.log('Data received from Db:\n');

        var string=JSON.stringify(rows);
        var json =  JSON.parse(string);

        console.log('>> MAX_ID: ', json[0].id);/* >> MAX_ID: 14 it is work successfully*/

        let name=getdata(json[0].id);
        console.log(">>getdata() : "+name); /* >>getdata() : undefined*/
   })
});


var MaxId;
function getdata(MaxId){
    var res;
    /*console.log('THIS IS MAX ',MaxId);*/
    con.query('SELECT * FROM users WHERE user_id = ?',[MaxId],(err,rows)=> {
       if(err)throw err;
       var string=JSON.stringify(rows);
       var json =  JSON.parse(string);

       r=json[0].user_first;
       //how i can return this varaible 
       //or move it outside con.query
    })
    return r;// r not defined
}

Upvotes: 0

Views: 64

Answers (2)

Syed
Syed

Reputation: 1

You can use async/await introduced in ES8 to do this.

app.post('/home.html',function(req,res){
   // pass request param to this new function
   handleRequest(params);
});

// handle request params here if you need to do so
async function handleRequest(params) {
   var userId = await getUserId();
   var data = await getData(userId);
}

async function getUserId()
{
  con.query('SELECT MAX(user_id) as id FROM users',(err,rows)=> {
    if(err) throw err;
    console.log('Data received from Db:\n');

    var string=JSON.stringify(rows);
    var json =  JSON.parse(string);

    console.log('>> MAX_ID: ', json[0].id);

    let name=getdata(json[0].id);
    return name;
    console.log(">>getdata() : "+name);
   })
}


var MaxId;
async function getdata(MaxId){
var res;

con.query('SELECT * FROM users WHERE user_id = ?',[MaxId],(err,rows)=> 
{
   if(err)throw err;
   var string=JSON.stringify(rows);
   var json =  JSON.parse(string);

   r=json[0].user_first;
   return r;
  })

}

This will do the trick. You might need to make few syntax adjustments. I haven't run it on my machine.

The problem with your code was that your query returns data asynchronously and by the time your query returns data, your function getData has already returned r since its synchronous. By using await, now both variables userId and data(used in my code) will be initialised only when the two functions have returned their data respectively

You can see the official documentation of async/await here Async/Await

Upvotes: 0

Mukesh Sharma
Mukesh Sharma

Reputation: 9022

You can use callback or promises to solve the problem. You can't return values from functions having asynchronous code.

You can define getdata to accept callback as an argument,

function getdata(MaxId, callback){
    // some code
    con.query('SELECT * FROM users WHERE user_id = ?',[MaxId],(err,rows)=> {
       // some code
       callback(r);
    });
})

and, then can use it in route.

app.post('/home.html',function(req,res){
    // some code
    con.query('SELECT MAX(user_id) as id FROM users',(err,rows)=> {
       // some code
       getdata(json[0].id, (name) => {
          console.log(name);
          // can write to res as well, like res.send(name);
       });
    });
});

Upvotes: 1

Related Questions