I want to check whether a username is already in use using pg-promise
.
I use the following query:
this.db.one('SELECT EXISTS(SELECT 1 FROM users WHERE username = $1)', username);
I am trying to encapsulate this query inside a function that simply returns true if the username exists, false if not.
Something like:
existsUsername(username){
this.db.one('SELECT EXISTS(SELECT 1 FROM users WHERE username = $1)', username)
.then(data => {
if(data.exists == true){
return true;
} else {
return false;
}
});
}
That I can simply use like so:
if(db.users.existsUsername(username)){
// this username is already taken
}
However the if condition is assessed before the query finishes, resulting in an undefined variable.
What is the proper way of returning the result of a query?
EDIT: the outer caller performs multiple async checks and returns whether the user is valid or not:
function signUp(username, email, ...){
// perform username existence check existsUser(username)
// perform email existence check existsEmail(username)
// ...
// if everything OK, put user in DB
}