I am trying to create a createUser function that should only create a user if no user is found with the chosen username (that is, the user does not exist). Also this function should return a promise that i would later handle.
This function findbyUsername is supposed to return a user with the username ONLY if the user exists.
I am banking on the case where the user does NOT exist because ONLY then can a NEW user with that username be created. (you cannot have two users with same username)
const findByUsername = (name) => {
return new Promise((res, rej) => {
pool.query(
"SELECT * FROM users WHERE username = $1",
[name],
(error, results) => {
if (error) {
rej("no user found");
}
console.log(results.rows);
res(results.rows[0]);
//return results.rows[0];
}
);
});
};
The function above resolves if the username exists and rejects if not. NOW HERES THE THING….. I want to chain this function to another function that will create a user ONLY when findByUsername is rejected. Pls how do i get my createUser function to run only when findbyUsername is rejected. Note that createUser will also return a new promise that will be resolved or rejected and so need to be handled
2
Answers
You can use
.then
and.catch
chaining to only execute the function.However I would recommend to do it like this using a guard state.
The same way as you would handle any rejection – with a
catch
method if chaining promises or atry...catch
if you’re working with async/await.For the purpose of demonstration my equivalent of your method just checks for my username and resolves with an id of 1 if that’s the input.
In both these cases you can return another promise and continue going with either async/await or chaining.