0

I have a client sending JSON information to the server and trying to make a register. JSON includes name and password of this user. Before the server makes the register into the database it needs to make sure that the username is available. For this purpose i created a function called isRegisted(req) that makes a search on the database and if the result.length is greater than zero then set a boolean value to true and at the end of the function returns this boolean value. The mysql search returns what it's expected in "result" but at the end the boolean value is not set and the console.log prints undefined.

Here's my code:

function register(req , res){
res.setHeader('Content-Type', 'application/json');
console.log(isRegisted(req));
}

function isRegisted(req){
var flag;
var query = conn.query("SELECT * FROM Users WHERE name=?", [  req.body.name ], function(err, result) {
        if(err){
            console.error(err);
            return;
        }
        console.log(result);
        if(result.length > 0)
            flag = true;
        else
            flag = false;
});
return flag;
}

Thank you for your attention.

2 Answers2

0

The problem with your code is, that you make an asynchronious request to the database. The function(err,result) will only be executed AFTER the query was done in your database. So you cannot be sure, when the function(err,result) will be called. So in mostly every case the flag is always undefined, because the database has not executed the query, which results in an undefined variable flag. The circumvent this problem, do your additional logic in the function(err, result) .

DZDomi
  • 1,685
  • 15
  • 13
-2

In this case, you have a async. function, so parent function doesn't wait for child function execution and returns undefined. Something like this may be useful for you:

        var successFn = function() {console.log('success');},
            errorFn = function() {console.log('error');};
        function register(req , res){
            res.setHeader('Content-Type', 'application/json');
            console.log(isRegisted(req, successFn, errorFn));
        }
        function isRegisted(req, successFn, errorFn){
            var flag;
            var query = conn.query("SELECT * FROM Users WHERE name=?", [      req.body.name ], function(err, result) {
            if(err){
             errorFn();
            }

            if(result.length > 0) {
             successFn();
            }        
    });
    }