user5506707
user5506707

Reputation:

return function variable in nodejs

How to pass the variable from function ??

This is my function, I did the query and get the result successfully I also confirmed that x=1 by console.log(x), So I can sure that x is set.

 function checktype(x){

     (Do something)

      var x = rows[0].type;  // [ RowDataPacket { type: 2 } ]
      return x; //x=2

};

Here is the API part. I use the function checktype() here but I cannot get the returned value. I also try to run checktype(a); only but I cannot get the result / x too.

 router.post("/check",function(req,res){
    var a = req.body.a;
    var result = checktype(a);

    console.log(result); //undefined 

 });

Upvotes: 0

Views: 686

Answers (1)

Guy Hagemans
Guy Hagemans

Reputation: 530

From your example I read that data is retrieved from a MySQL database. This is an asynchronous operation, so you have to add a callback or promise.

So when you are sure your function is running synchronous code, then you can safely use 'return x', else node will continue with the code after 'var x ='

Please note that making functions synchronous is generally bad for performance.

so for this function, add a callback:

function checktype(x, callback){
    mysql.query(query, function (error, rows, fields) {
        if (error) {
            callback(error,0);
        } else {
           var x = rows[0].type;  // [ RowDataPacket { type: 2 } ]
           callback(0,x);
        }
    });
};    

And then call this function and handle the callback;

router.post("/check",function(req,res){
        var a = req.body.a;
        checktype(a, function(error, x){
            if (error){
                res.status(500).send({"message" : "internal server error"});
            }
             else{
            res.status(200).send(x);
            onsole.log(result); //undefined 
          }
        };
     });

Hope this helps! (sorry about the indentation)

Upvotes: 1

Related Questions