This solution is generated by ChatGPT, correctness is not guaranteed.

AI solution for JavaScript Coding Question on BFE.dev
123. implement Promise.prototype.finally()

Here is an implementation of Promise.prototype.finally():

Promise.prototype.finally = function (callback) {
  return this.then(
    // Case 1: Promise is successfully resolved
    (value) => Promise.resolve(callback()).then(() => value),
    // Case 2: Promise is rejected
    (error) =>
      Promise.resolve(callback()).then(() => {
        throw error;
      })
  );
};

This implementation adds a finally() method to the Promise.prototype object, which takes a callback as an argument. It returns a new promise that is resolved with the same value as the original promise (in case the promise was fulfilled) or rejected with the same error as the original promise (in case the promise was rejected).

In either case, the callback() is called without any argument. If the promise was fulfilled, the callback() is called and its result is ignored. If the promise was rejected, the callback() is still called and its result is ignored. The callback is called either way and it doesn't have any effect on the promise value (care for rejection).

Note that, as with other methods that return a new promise, the original promise is not modified.