Be the first user to complete this post

  • 0
Add to List

Error handling in promises interview question

Let's quickly revise some of the fundamentals of the promises, before we jump into the best practices and anti-patterns for error handling in JavaScript promises.

What is a promise?

  • It is an object which will return a single value at some time in the future: either a resolve or rejected value.

  • It has three possible states:

    • resolved
    • rejected
    • pending resolve or rejected promise is also called as a settled promise.
  • Promises are eager, meaning they will start the work as soon as the promise constructor is called. Observables and Tasks are lazy implementations.

  • A promise object supplies a .then() method, which must return a new promise. For example,

const wait = time => new Promise((resolve) => setTimeout(resolve, time));

wait(3000)
  .then(() => console.log('Hello'))
  .then(() => console.log('World'))
  .catch(() => console.error('Error'));

Here, when the callback prints the 'Hello', at that point the promise object returned by wait() is resolved. And .then() returns a new promise on which we can call .then() again. This allows us to create a promise chain. At this point we have all the fundamentals we need to work on promises. Let's dive in to the error handling of the promises.


Error handling in promises

.then() on promise object takes two functions as an arguments which looks like the following:
somePromise()
    .then(resolveCallback, rejectCallback)
Above pattern will catch the error thrown by somePromise(), potential errors are network errors. But what about the errors thrown by resolveCallback, potential errors are exceptions thrown by unhandledd status codes. Those errors will be swallowed, OOPS! Hence, above pattern is called an anti pattern. The better way to handle errors is using the following pattern.
somePromise()
    .then(resolveCallback)
    .catch(rejectCallback)
In this pattern we can catch potential errors caused in somePromise() and resolveCallback both in the rejectCallback handler inside the catch block.

What if you want to catch both the error cases seperately?

somePromise()
    .then(resolveCallback, networkErrorCallback)
    .catch(rejectCallback)
Here, the network errors will be handled inside the networkError callback. And everyother error will be handled by rejectCallback inside the catch block. General rule of thumb is the following:
End every promise chain with the .catch() call back.

Further reading



Also Read:

  1. Generating container components with connect utility in react redux app
  2. Array filterUntil function implementation for javascript
  3. JavaScript Promises - Visualized
  4. center using css
  5. position: relative