Break a promise chain using throw-catch

Viewed 60

I need to check if the user is present in two databases and if not present, I have to create a new user.

Check if the user is present in the database 1. If it is present throw a "user exists" and catch it without executing the rest of the other then().

Check if the user is present in the database 2. If it is present throw a "user exists" and catch it without executing the rest of the other then().

Else if it is not present, create the user.

I was trying to break a promise chain. Here is the scenario. So what I did is

const promise = new Promise((resolve, reject) => {
       resolve(false); 

   }).then(value => {
         //check if user exists in table 1 and set value to True or False
         if (value==True){
             throw "User exists";
         }
         else{
              return value;
         }
   }).then(value=> {
      ////check if user exists in table 2 and set value to True or False
      if (value==True){
             throw "User exists";
         }
         else{
              return value;
         }
   }).catch(err => {
           console.log(err);
       });

This is how it looked briefly.

But it doesn't stop executing the later then() statements even if i throw a message. It keeps on executing the entire code even if the user is found.

And it also shows the below and stops the entire execution.

                    throw 'user found'
                    ^

Note: There is something I have to do with the user values after i get them. So the execution should not be stopped.

1 Answers

Instead of throw use return Promise.reject(new Error()). BTW - if you throw you should throw new Error('message').

But this is how errors should be handled not logic of code execution.

checkIfUserExistsInDB1() //this must be a function returning a promise
  .then(user => {
    if (!user) return checkIfUserExistsInDB2() //this must be a function returning a promise
    else return Promise.resolve(user)
  })
  .then(user => {
    if (!user) return createUser() //this must be a function returning a promise
    else return Promise.resolve(user)
  })
  .then(user=> { do whatever you need more })
  .catch(err => { handle error }) 
Related