Coding Challenge Practice - Question 116
Source: Dev.to
Problem Statement
Implement Promise.prototype.finally() so that a callback is executed when a promise is settled (either fulfilled or rejected).
Boilerplate
function myFinally(promise, onFinally) {
// your code here
}
Implementation Details
- Attach
.thento the original promise. - For the fulfillment case, invoke
onFinally(if provided), ensure it returns a promise withPromise.resolve, then forward the original value. - For the rejection case, invoke
onFinally(if provided), ensure it returns a promise withPromise.resolve, then re‑throw the original error.
Fulfilled Path
(value) => {
return Promise.resolve(onFinally && onFinally()).then(() => value);
}
Promise.resolve converts a normal value to a resolved promise, allowing the onFinally callback to be handled uniformly.
Rejected Path
(error) => {
return Promise.resolve(onFinally && onFinally()).then(() => {
throw error;
});
}
Final Code
function myFinally(promise, onFinally) {
return promise.then(
(value) => {
return Promise.resolve(onFinally && onFinally()).then(() => value);
},
(error) => {
return Promise.resolve(onFinally && onFinally()).then(() => {
throw error;
});
}
);
}