Why doesn't Promise.prototype.finally() receive any arguments?
The documentation says:
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
However, i can add a simple method to the Promise prototype, lets name it finally2 (Promise.prototype.finally2) which can receive the result, and can reliably determine if the promise was fulfilled or rejected.
Promise.prototype.finally2 = function(callback){
return this.then(result => callback(result), result => callback(undefined, result));
}
I understand (as the documentation says) that the use case for Promise.prototype.finally is precisely when you do not care about the rejection reason, or the fulfillment value.
My question is: How is it unreliable to determine if the promise was fulfilled or rejected in Promise.prototype.finally?
Promise.prototype.finally2 = function(callback){
return this.then(result => callback(result), result => callback(undefined, result));
}
Promise.resolve(2).finally((...args) => console.log('finally:resolve =>', args));
Promise.reject(2).finally((...args) => console.log('finally:reject =>', args));
Promise.resolve(2).finally2((...args) => console.log('finally2:resolve =>', args));
Promise.reject(2).finally2((...args) => console.log('finally2:reject =>', args));
It is possible to reliable determine whether a promise was fulfilled or rejected, using .then(…, …). Your implementation shows that (although it is unfaithful about the return value, compare the native finally resolving to the original result when the callback doesn't throw).
But you're right, the reasoning of the section you quoted is garbage. And indeed, in the years since your question, MDN has been updated and now only says
The
onFinallycallback does not receive any argument. 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.
That's really all there is to say. The finally method is used when you do not care about the outcome of the promise, just like a finally block on a try. If you did care, you wouldn't (shouldn't) use finally in the first place.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With