Cerulean
Cerulean

Reputation: 6013

What is the difference between using Promise.catch() and wrapping a Promise in try...catch?

I was sitting in listening to a Javascript class today and they were covering something I hadn't seen before and which I don't fully understand. I will try to reproduce as best I can from memory

Instead of using the catch of a Promise to handle errors, which I'm used to, the teacher used try...catch wrapped around the Promise and its thens. When I asked him why he did this, he said it was to catch the error 'synchronously'. That is, instead of the following format (I'm using pseudocode), which I'm used to

someLibrary.someFunctionThatReturnsAPromise
.then(() => something)
.then(() => somethingElse)
.catch(err => reportError)

he did it thus

try {
 someLibrary.someFunctionThatReturnsAPromise
    .then(() => something)
    .then(() => somethingElse)
} 
catch(err) {
  reportError
}

What would be the difference between these two ways of catching the error? How would wrapping a Promise, which is asynchronous, report errors in a synchronous fashion?

Thanks for any insights!

Upvotes: 4

Views: 1831

Answers (3)

tavkiev
tavkiev

Reputation: 63

  1. catch after then (first example) it is a short way to to handle only error from your promise. It is the same as .then(null, (err) => reportError) as then takes two parameters: for fulfilled and rejected state of the promise.
  2. try catch block (second example) in short - is is a common way to handle your code block. if you what from your code not only failed but do something after it. Try/catch is working only in sync mode, that is why if you work with async code, you should wrap it, for example in async/await way.

Actually you can also you use 3 statement after catch - finally, but it depends )

Upvotes: 1

Matthew Herbst
Matthew Herbst

Reputation: 31983

The try-catch won't catch asynchronous errors around a <somePromise>.then since as you've noticed, the block will exit before the promise has finished/potentially thrown.

However, if you are using async/await then the try-catch will catch since the block will wait for the await:

async function foobar() {
  try {
    await doSomePromise();
  } catch (e) {
    console.log(e);
  }
}

Upvotes: 3

CertainPerformance
CertainPerformance

Reputation: 370759

The try/catch version will only catch the error if the error is thrown when the initial (synchronous) code is running - it will not catch errors that are thrown inside any of the .thens:

try {
  Promise.resolve()
    .then(() => {
      throw new Error()
    });
} catch(e) {
  console.log('caught');
}

So, the only way an error will be caught with try/catch in your code is if someLibrary.someFunctionThatReturnsAPromise throws synchronously. On the other hand, the .then/.catch version will catch any error (and is almost certainly preferable).

Upvotes: 1

Related Questions