Coding Challenge Practice - Question 116

Published: (February 7, 2026 at 12:30 PM EST)
1 min read
Source: Dev.to

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 .then to the original promise.
  • For the fulfillment case, invoke onFinally (if provided), ensure it returns a promise with Promise.resolve, then forward the original value.
  • For the rejection case, invoke onFinally (if provided), ensure it returns a promise with Promise.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;
      });
    }
  );
}
0 views
Back to Blog

Related posts

Read more »