0

What am I missing?

try {
} catch (error){
}

My understanding is that when a code in the try block throws an error, then the program loops through the code in the catch block and the error is captured in the error identifier.

Now consider this code snippet

async function hostDinnerParty(){
  try {
    let meal = await cookBeanSouffle();
    console.log(`${meal} is served!`);
  } catch(error){
    console.log(error);
    console.log('Ordering a pizza!');
  }
}

When I call hostDinnerParty() , cookBeanSouffle() returns a promise that can randomly either reject or resolve! When it resolves the try block runs, but when it rejects the catch block runs telling me indirectly that the reject state of the promise is indeed similar to an error being thrown as only when we throw error we can loop through the catch block.

Before this I never looked at the reject state of a promise being equivalent to an error. Is my understanding of this correct?

What am I missing?

  • I don't think you're missing anything. Throwing is indeed the same as rejecting a promise. When you use `await` rejections are handled in a `catch` block. If you're using the promise API, then rejections go in the `.catch()` callbacks. – VLAZ Mar 11 '21 at 20:05
  • @VLAZ thanks for your answer, I am new to JS and yet to connect all the dots across different concepts. – Naren Dhyani Mar 11 '21 at 20:24
  • 1
    Have a look at [Why are exceptions used for rejecting promises in JS?](https://stackoverflow.com/q/21616432/1048572) and [Why is it possible to try-catch an async-await call?](https://stackoverflow.com/q/52434252/1048572) – Bergi Mar 11 '21 at 23:30
  • "*I never looked at the reject state of a promise being equivalent to an error*" - what else would it be used for? – Bergi Mar 11 '21 at 23:31

0 Answers0