The task is to implement Promise.prototype.finally()
The boilerplate code
function myFinally(promise, onFinally) {
// your code here
}
Promise.prototype.finally() could be used to return a callback when a promise is settled (fulfilled or rejected).
Attach .then to resolve the promise
return promise.then(
If the promise was fulfilled
(value) => {
return Promise.resolve(onFinally && onFinally()).then(() => value)
}
Promise.resolve is used because it converts normal value to a resolved promise.
If the promise is rejected
(error) => {
return Promise.resolve(onFinally && onFinally()).then(() => {
throw error
}
The final code
function myFinally(promise, onFinally) {
// your code here
return promise.then(
(value) => {
return Promise.resolve(onFinally && onFinally()).then(() => value);
},
(error) => {
return Promise.resolve(onFinally && onFinally()).then(() => {
throw error
})
}
)
}
That's all folks!
Top comments (0)