Be the first user to complete this post
|Add to List|
Error handling in promises interview question
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:
resolve or rejected promise is also called as a
- 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:
Above pattern will catch the error thrown by
somePromise() .then(resolveCallback, rejectCallback)
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.
In this pattern we can catch potential errors caused in
somePromise() .then(resolveCallback) .catch(rejectCallback)
resolveCallbackboth in the
rejectCallbackhandler inside the
What if you want to catch both the error cases seperately?
Here, the network errors will be handled inside the
somePromise() .then(resolveCallback, networkErrorCallback) .catch(rejectCallback)
networkErrorcallback. And everyother error will be handled by
rejectCallbackinside the catch block. General rule of thumb is the following:
End every promise chain with the
- Passing the store down implicitly via context in a react redux app
- exports is not defined
- center using css
- Default function parameters
- Dynamic module loading with require
- gzip compress and cache api response in express
- Testing promise sequence using mocha, chai, chai-as-promised, sinon