Promise.finally() Polyfill
The finally() method of a Promise schedules a function, the callback function, to be called when the promise is settled. Like then() and catch(), it immediately returns an equivalent Promise object, allowing you to chain calls to another promise method, an operation called composition.
Promise.prototype.finallyPolyfill = function (callback) {
return this.then(
(value) => {
callback();
return value;
},
(error) => {
callback();
throw error;
}
);
};
Example
function example(time) {
return new Promise((resolve, reject) => {
if (time >= 1000) {
resolve("Resolved");
} else {
reject("rejected");
}
});
}
example(2000)
.then((val) => console.log(val))
.catch((err) => console.log(err))
.finallyPolyfill(() => console.log("All Completed"))
.then(() => console.log("Chained then"))
// Resolved
// All Completed
// Chained then