skip to Main Content

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


  1. You can use .then and .catch chaining to only execute the function.

    findByUsername("")
    .then(() => doSomethingElse())
    .catch(() => createUser())
    
    

    However I would recommend to do it like this using a guard state.

    
    const user = await findByUsername("").catch(() => undefined); // return user or undefined if err
    
    if (user === undefined){
     return createUser();
    }
    
    return doSomethingElse();
    
    
    Login or Signup to reply.
  2. The same way as you would handle any rejection – with a catch method if chaining promises or a try...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.

    const findByUsername = (name) => {
      return new Promise((res, rej) => {
        if(name === "jamiec"){
          res(1)
        }
        else{
           rej("No user found");
        }
      });
    };
    
    // async await
    
    async function doAsyncAwait(username){
         try{
            var result = await findByUsername(username);
            console.log(`User ${username} found with id ${result}`);
         }
         catch{
            console.log(`User ${username} not found - go ahead and create this user`);
         }
    }
    
    doAsyncAwait("jamiec")
    doAsyncAwait("bob")
    
    function doChain(username){
         findByUsername(username)
         .then( result =>  console.log(`User ${username} found with id ${result}`))
         .catch(() => console.log(`User ${username} not found - go ahead and create this user`))
    }
    
    doChain("jamiec");
    doChain("bob");

    In both these cases you can return another promise and continue going with either async/await or chaining.

    const findByUsername = (name) => {
      return new Promise((res, rej) => {
        if(name === "jamiec"){
          res(1)
        }
        else{
           rej("No user found");
        }
      });
    };
    
    const createUser = (name) => {
       // simulate creating a user
       return new Promise(res => res(2));
    }
    
    // async await
    
    async function doAsyncAwait(username){
         try{
            var result = await findByUsername(username);
            return result;
         }
         catch{
            return await createUser(name);
         }
    }
    
    (async function() {
      var id1 = await doAsyncAwait("jamiec")
      console.log(id1);
      var id2 = await doAsyncAwait("bob")
      console.log(id2);
    })();
    
    function doChain(username){
         return findByUsername(username)
          .catch(() => createUser(username))
    }
    
    doChain("jamiec").then(id => console.log(id));
    doChain("bob").then(id => console.log(id));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search