1

I'm trying to check if a username is taken in a node.js application. For some reason I can't set a variable after I do "db.get..". I want to be able to set the "taken" based on if the name was taken or not, or if there was an error.

I'm not that familiar with asynchronous calls, and I'm not really sure what is actually asynchronous about this. I've read about asynchronous calls here and here, but I still Can't wrap my head around it. I'm having a hard time implementing it into my code.

I'm using sqlite3 and a local database file to test it on.

function isUsernameTaken(username) {
    console.log("checking username");
    query = "SELECT * FROM `account` WHERE username = ?";
    let taken = true
    db.get(query, [username], function(error, post){
        if(error){
            console.log("error: "+ error);
            taken = 500;
        }
        else{
            console.log("the post: " +post);
            if(post === undefined || post.length == 0 || !post){
                taken = false  
            }
        }
    })
    console.log("Name taken?: " +taken);
    return taken;
}

I expect to be able to return the variable taken, but it always returns as

true

0 Answers0