1

What I want to do is to execute some sync/async functions back-to-back in the chain and - if something is not right - reject this function, catch this rejection in the catch method at the end of the chain and simply throw an exception for the user. I'm writing a module and I want the user to have some messages thrown if he/she configure the module incorrectly.

When I try to throw an Error in the Promise catch method, it returns UnhandledPromiseRejectionWarning: Unhandled promise rejection exception. As I found out, the JS 'treats' the throw similarly to reject() and it expects another catch method attached at the end of the following chain to 'catch' this thrown Error, what seems to be a little confisung to me, or maybe I don't get the idea of promises...

test()
.then(()=>{
  console.log('success!');
})
.catch((msg)=>{
  throw new Error(msg);
});
//it expects another catch here to 'catch' the thrown error
//if I attach another catch() here
//then the 'UnhandledPromiseRejectionWarning' is not displayed
//but Error is still not thrown, just caught by another catch()

function test(){
  return new Promise((resolve,reject)=>{
    setTimeout(()=>{
      reject('you set incorrect type!');
    },300);
  });
}

I could throw an error directly in the Promise object in order to throw an exception and terminate the chain flow as I want, but what I've also found a little confusing is that I can use throw only asynchronously in the Promise object to throw an exception. If I throw synchronously, the Promise catch() method catches this exception.

This throws error: (which is desirable)

function test(){
  return new Promise((resolve,reject)=>{
    setTimeout(()=>{
      throw new Error('async aborted!'); 
    },300);
  });
}

This executes Promise catch(): (which is not desirable)

function test(){
  return new Promise((resolve,reject)=>{
    throw new Error('sync aborted!');
    setTimeout(()=>{

    },300);
  });
}

So, to sum up, I try to figure out how to to throw Error without getting UnhandledPromiseRejectionWarning: Unhandled promise rejection exception? In the try catch block I can simply re-throw an exception, why I can't do so in the Promise chain?

Roamer-1888
  • 18,384
  • 5
  • 29
  • 42
Paweł
  • 3,261
  • 2
  • 14
  • 31

0 Answers0