Predict when Promise finally preserves or replaces an outcome. Test thrown cleanup, rejected promises, deferred completion and retained secondary diagnostics.

Author: PracHub

Published: 11/29/2026

JavaScript Promise Interview: Why Does finally Sometimes Replace the Original Failure?

November 29, 2026

Quick Overview

finally preserves the original settlement only when its callback completes successfully; a thrown error or rejected returned promise replaces it, while a fulfilled cleanup can delay without replacing the value.

Frontend EngineerFree

finally preserves the original fulfillment value or rejection reason only when its cleanup callback completes successfully. A thrown cleanup error or a rejected promise returned by cleanup becomes the new rejection. Successful asynchronous cleanup can also delay the result without changing its value.

Start with Implement a Promise Class in JavaScript with then Chaining, catch and finally and predict the returned promise's settlement for each cleanup outcome. PracHub publishes this original rehearsal; the linked questions provide adjacent practice rather than evidence of a company's interview process.

The ECMAScript and MDN references were checked on November 28, 2026. We executed the controls below in Node v26.9.0 with synthetic errors and an explicitly released promise gate. These observations concern promise settlement, not guaranteed cleanup after a process crash or the behavior of an external resource service.

Promise finally preserves the original outcome after successful cleanup but replaces it when cleanup throws or rejects

Observe the promise returned by finally

The expression operation.finally(cleanup) returns another promise. The question is what settles that returned promise, not whether the original operation can be retroactively changed.

The ECMAScript finally algorithm defines the reactions attached to the original fulfillment and rejection. MDN's finally reference describes the common transparent-settlement behavior and its exceptions.

When a callable cleanup runs successfully, its ordinary return value is not a replacement business result. If the original operation fulfilled with value and cleanup returns 99, the returned promise still fulfills with value.

If the original operation rejected, successful cleanup preserves the original rejection reason. Our control used an Error object and verified object identity, not merely matching message text. The caught reason was the same original object.

Cleanup can itself fail. A thrown value or returned rejected promise determines the returned promise's rejection. That is why a caller can catch a cleanup failure while losing the original operation's failure from the direct rejection channel.

Build a settlement matrix before writing the repair

Our controls used one original Error and a different cleanup Error so that identical messages could not hide which reason survived. Both errors were synthetic, with no production stack or customer data involved.

Original outcomeCleanup behaviorObserved returned outcome
Fulfilled with valueReturns 99Fulfilled with original value
Rejected with original ErrorCompletes successfullyRejected with the same original Error
Rejected with original ErrorThrows cleanup ErrorRejected with cleanup Error
Fulfilled with valueReturns a rejected cleanup promiseRejected with cleanup Error
Rejected with original ErrorReturns a rejected cleanup promiseRejected with cleanup Error
Fulfilled with valueReturns a fulfilled promise containing another valueFulfilled with original value

These are executed Node outcomes. They do not require a timer, an HTTP request or assumptions about thread scheduling. Each assertion waited for the returned promise and checked its value or rejection identity.

The fulfilled cleanup-promise row rejects another common misconception: “Returning a promise makes its fulfillment value replace the original.” Its settlement must be awaited, but successful cleanup still passes through the original outcome.

An interviewer can change only one cell, such as replacing return 99 with throw 99. Predict that cell from the rule rather than memorizing the table. The return completes successfully; the throw introduces an abrupt completion and changes the returned rejection.

Do not implement finally as then(cleanup, cleanup)

MDN's then reference explains how handler return values affect a chained promise. An ordinary then handler's returned value becomes the chain's new fulfillment value.

That makes this apparent shortcut incorrect for transparent cleanup:

Promise.resolve('result').then(
  () => 99,
  () => 99
); // fulfills with 99

The corresponding finally(() => 99) preserves result. Also, a callable finally callback receives no fulfillment value or rejection reason. It is not a success or error transformer with the same arguments as the two then handlers.

A teaching sketch can illustrate the required pass-through behavior:

function illustrateFinally(promise, cleanup) {
  return promise.then(
    value => Promise.resolve(cleanup()).then(() => value),
    reason => Promise.resolve(cleanup()).then(() => {
      throw reason;
    })
  );
}

This sketch assumes a callable cleanup and native Promise usage. It is not a complete specification-compatible polyfill: it does not implement every constructor, species or non-callable case. The executed matrix used native finally, not this helper.

The nested then matters. Successful cleanup leads to the saved original value or reason. A cleanup throw or rejection interrupts that path and propagates its own rejection. If you remove the nested pass-through handler, you change the behavior the interview is testing.

Prove asynchronous cleanup delays observation

We created a pending promise gate whose resolver was retained by the test. The cleanup callback recorded cleanup started and returned that gate. A reaction on the final returned promise recorded outcome observed.

Before releasing the gate, the returned outcome had not been observed. We then recorded release cleanup and resolved the gate. The completed event order was:

cleanup started
release cleanup
outcome observed

The final fulfillment still contained the original value. The gate establishes both facts: asynchronous cleanup can delay the chain, and successful cleanup does not replace the original value with the gate's fulfillment value.

This test is stronger than waiting an arbitrary number of milliseconds and hoping cleanup finished first. It controls the dependency directly. We did not make a measured latency claim or extrapolate a production timeout from the ordering.

If cleanup never settles, the chained promise can remain pending even though the original operation already completed. That follows from the documented waiting behavior; our control released the gate and did not run an indefinite hanging test.

An application that needs a bounded wait must define that policy explicitly. A timeout wrapper changes what completion means and may leave cleanup running elsewhere. Merely adding finally does not supply a resource deadline or cancellation protocol.

Original settlement matrix and controlled cleanup gate separate replacement from delayed pass-through

Choose which failure the caller should receive

There is no universal rule that a cleanup failure must be hidden. Suppose an operation succeeds but releasing a critical resource fails. The caller may need that failure. In another application, an optional telemetry flush should not replace a useful operation error.

Write the policy before changing the chain. Our additional executed control retained the original operation failure and recorded cleanup failure separately:

const secondaryErrors = [];
const original = new Error('operation failed');
const cleanupError = new Error('cleanup failed');

await Promise.reject(original).finally(async () => {
  try {
    throw cleanupError;
  } catch (error) {
    secondaryErrors.push(error);
  }
}).catch(reason => {
  if (reason !== original) throw new Error('wrong primary error');
});

The control observed the original rejection at the caller and the cleanup Error in the secondary list. Catching cleanup's failure made that callback complete successfully, restoring the pass-through behavior.

This is an explicit choice, not automatic error aggregation. Native finally does not construct an AggregateError containing both failures. If the product needs both in one structured result, design that structure and test its ordering and caller contract.

A real reporting function can also fail. Decide whether reporting is best effort, awaited or critical; otherwise a new reporting throw can become yet another replacement error. The synthetic list push in this control avoids pretending that an external logger is infallible.

Separate awaited cleanup from detached work

Cleanup affects the chained result when its failure is thrown or represented by the value it returns. Starting an asynchronous operation and returning nothing does not automatically make the chain await that detached operation.

For example, a callback that calls flushTelemetry() without returning or awaiting its promise expresses different sequencing from return flushTelemetry(). The latter makes the flush settlement part of the cleanup path; the former leaves its later outcome outside that returned chain.

This is a proposed extension, not another measured row from our gate test. In a regression, use a second controlled promise to show whether the final outcome waits for the flush. Observe any detached rejection separately rather than assuming the original catch will receive it.

Avoid describing finally as a guarantee that cleanup completes under every exit. The callback is a promise reaction inside a running JavaScript environment. Process termination, a crash or an external resource protocol can prevent the desired cleanup effect even when the language-level chain is correct.

The interview should stay precise: this mechanism sequences reactions and adopts cleanup settlement. Durability and remote release confirmation belong to the resource's own contract.

Put the caller's catch on the chain it intends to observe

Keeping a reference to the original promise does not automatically observe a rejection introduced by a later finally. The original operation and the promise returned by cleanup are different objects with potentially different outcomes.

A proposed regression would retain both references, attach explicit outcome observers and make cleanup reject. It should assert that the original fulfilled operation remains fulfilled while the chained result rejects. This isolates settlement from error-message wording and makes it clear why a catch attached only to the original promise cannot handle every later cleanup failure.

Chain placement also affects recovery. A catch before finally can convert the original failure into a fulfilled recovery value; successful cleanup then preserves that recovery value. A catch after finally sees the outcome after cleanup's pass-through or replacement. Choose the placement according to the caller contract rather than moving catches until a test stops printing an error.

These are language-level extensions of the executed matrix, not additional claims about the gate control. Their value is to give a custom Promise implementation a test that distinguishes original settlement, recovery and cleanup settlement as separate stages.

Include the non-callable control when implementing a Promise

Our native control also called finally(123) on a promise fulfilled with 12. The result remained 12. A non-callable argument is not invoked as a cleanup function and should not be implemented as an unconditional function call.

That edge case matters if the task is to implement a Promise-like class. A helper that does cleanup() without checking its contract will throw for the non-callable case and diverge from native behavior.

Keep the implementation scope explicit. A small interview class may intentionally support a subset, but the tests should say which features are excluded. Do not label the illustrative helper above a complete polyfill merely because it passes the ordinary callable matrix.

For a concise defense, walk through one original rejection, successful cleanup preserving object identity, cleanup rejection replacing it and the deferred gate delaying observation. Those four cases expose most incorrect mental models without relying on incidental error-message wording.

Rehearse the matrix in Implement a Promise Class in JavaScript with then Chaining, catch and finally, then state whether your chosen application policy exposes cleanup failure, records it separately or combines errors through an explicit contract.

PracHub questionWhat to practise
Implement a Promise Class in JavaScript with then Chaining, catch and finallyImplement finally settlement rather than treating it as another then.
Run Promise Tasks with Bounded ConcurrencyPreserve task failures while worker cleanup completes.
Explain JS types, Promises, Maps, WebSocketsDistinguish a fulfilled value from an adopted rejection.
Name-Keyed Async Task Scheduler with Sequential Lanes, Cancel and Clear by NameDefine what cancellation cleanup changes in a task lane.
Explain JS event loop and related conceptsTrace promise reactions and the final observed outcome.

Use the Promise implementation question for settlement behavior and the schedulers for sequencing consequences. These links do not establish that every scheduling task needs the same cleanup policy.

Sources and Further Reading


Comments (0)