0

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 

 });
4
  • For var x = rows[0].type; , the type is real key for rows[0]? Also confused with }); in the checktype function, some typo? Commented Feb 23, 2016 at 7:40
  • Yes , because thats mysql result . " }); " is typo Commented Feb 23, 2016 at 7:45
  • this var x = rows[0].type; in the callback function right? Commented Feb 23, 2016 at 7:50
  • Do you have any asynchronous calls in function checktype ? Commented Feb 23, 2016 at 7:54

1 Answer 1

1

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)

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

Comments

Your Answer

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