PROMISE FINALLY() DEFINITION
Formerly, there were only inelegant ways of defining behavior that would execute after a promise exits the “pending” state no matter the outcome. Usually, this would take the form of recycling the handler:
let resolveA, rejectB;
function finalHandler() {
console.log('finished');
}
function resolveHandler(val) {
console.log('resolved');
finalHandler();
}
function rejectHandler(err) {
console.log('rejected');
finalHandler();
}
new Promise((resolve, reject) => {
resolveA = resolve;
})
.then(resolveHandler, rejectHandler);
new Promise((resolve, reject) => {
rejectB = reject;
})
.then(resolveHandler, rejectHandler);
resolveA();
rejectB();
// resolved
// finished
// rejected
// finished
With Promise.prototype.finally()
, you are able to unify the shared handler. The finally()
handler is not passed any arguments and does not know if it is handling a resolved or rejected promise. The preceding example...