Skip to content

Javascript Promises catch block not working?

I am trying to make a function that calls promises synchronously so that if any of them return false the execution stops and returns the reject object with the reason why the promise returned false.

Right now I am getting the error: UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason “#”.

What am I doing wrong?? I have been trying to get this to work for an hour. Do I have to return an Error object??

// call the function in my route

router.post('api/address', async (req, res) => {
      const status = await claimCheck()

     if (status.allowed = false) { // do something }   
})


const claimCheck = async () => {
  
  try {
    
   // run these synchronously so if promise fails/rejects/returns false, execution stops
    await allowedArea() 
    await validSubscription() 

   // IF ALL PASS return success object
   return {allowed: true, reason: "PASS"}
  } catch (err) {

     console.log(err.reason) 
    // If a promise rejects, I want to access the reject object properties here
    return err
  
  }
}

// PROMISE 1 - SHOULD REJECT

const allowedArea = new Promise(function (resolve, reject) {
  console.log("CLAIM COORDS ALLOWED AREA CHECK")
  const allowed = false

  if (allowed == false) {
    reject({ allowed: false, reason: "Area blocked" })
  }
  resolve()
})

// PROMISE 2 - SHOULD REJECT
const validSubscription = new Promise(function (resolve, reject) {
  const allowed = false

  if (allowed == false) {
    reject({ allowed: false, reason: "Bad Subscription" })
  }
  resolve()
})


Answer

As mentioned in comments allowedArea and validSubscription are not functions. you should just await on them without executing:

await allowedArea;
await validSubscription;

The function that you pass as an argument to a promise will be executed as soon as you instantiate it.

Also you are using consts allowedArea and validSubscription (same as claimcheck func ) before you declare them, which means just the var declaration will be hoisted up, but not it’s initialization, you should move the declarations to top. see more here

If you want to declare in the bottom, you can declare them as async function ... instead of new Promise this way it will be all hoisted up;