Difference Between Finally() And Then() In Es2018
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 withundefined
),Promise.resolve(2).finally(() => {})
will be resolved with2
.- Similarly, unlike
Promise.reject(3).then(() => {}, () => {})
(which will be fulfilled withundefined
),Promise.reject(3).finally(() => {})
will be rejected with3
.
Post a Comment for "Difference Between Finally() And Then() In Es2018"