Skip to content Skip to sidebar Skip to footer

Difference Between Finally() And Then() In Es2018

Before ES2018, I used to nest an extra then at the end of the promise chain whenever I had to perform any clean up logic that I'd otherwise duplicate in then and catch above, e.g.

Solution 1:

A then callback doesn't execute when the promise is rejected - and that can happen even for a promise returned by a catch invocation: when its callback throws or returns a rejected promise. err => console.error(err) is probably not going to do that, but you never know.

Similarly, I would recommend to favour .then(…, …) over .then(…).catch(…) if you only want to handle errors from the original promise, not from the then callback. I'd write

promise.then(console.log, console.error).finally(() =>console.log('Finally'));

The other more or less obvious differences are in the signature: the finally callback doesn't receive any arguments, and the promise that p.finally() returns will fulfill/reject with the same result as p (unless there's an exception or returned rejection in the callback).

Solution 2:

finally() executes whether the promise is fulfilled or rejected. Maybe the MDN doc's example will help.

Edit: the MDN doc gives these differences from then():

The finally() method is very similar to calling .then(onFinally, onFinally) however there are couple of differences:

  • When creating a function inline, you can pass it once, instead of being forced to either declare it twice, or create a variable for it
  • A finally callback will not receive any argument, since there's no reliable means of determining if the promise was fulfilled or rejected. This use case is for precisely when you do not care about the rejection reason, or the fulfillment value, and so there's no need to provide it.
  • Unlike Promise.resolve(2).then(() => {}, () => {}) (which will be resolved with undefined), Promise.resolve(2).finally(() => {}) will be resolved with 2.
  • Similarly, unlike Promise.reject(3).then(() => {}, () => {}) (which will be fulfilled with undefined), Promise.reject(3).finally(() => {}) will be rejected with 3.

Post a Comment for "Difference Between Finally() And Then() In Es2018"