Promise finally Runs Cleanup On Both Paths

finally registers cleanup that runs on fulfillment and rejection alike, leaves the original result untouched, and keeps cleanup logic out of then and catch.

JavascriptResilience

Code

javascriptsnippet
29 lines
// A finally callback runs on both the success and failure paths and leaves the original result untouched
function load(ok) {
  return Promise.resolve('payload').then((value) => {
    if (!ok) throw new Error('network down');
    return value;
  });
}

async function main() {
  let cleaned = 0;
  const okResult = await load(true).finally(() => {
    cleaned += 1;
  });
  console.log('ok:', okResult, '| cleanup count:', cleaned);

  try {
    await load(false).finally(() => {
      cleaned += 1;
    });
  } catch (err) {
    console.log('err:', err.message, '| cleanup count:', cleaned);
  }

  // The fulfilled value returned from finally is ignored: swap results via then/catch
  const passthrough = await Promise.resolve('value').finally(() => 'ignored');
  console.log('passthrough:', passthrough);
}

main();

Output

Captured from a sandboxed run of this snippet in the build pipeline.

ok: payload | cleanup count: 1
err: network down | cleanup count: 2
passthrough: value

How it works

Promise finally Runs Cleanup On Both Paths comes down to the functions load and main.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. Error is the guard’s signal — thrown at the branch, before any partial work happens.

What to watch for

  • The guard !ok short-circuits the flow with an early throw when its condition holds.

Applying it

Entry signature: function load(ok)

Look for the ok:, err:, passthrough: prefixes when the file runs; they tie each line to its step.

Start the program and main runs load one after another.

Statements that matter

const passthrough = await Promise.resolve('value').finally(() => 'ignored');
return Promise.resolve('payload').then((value) => {
if (!ok) throw new Error('network down');
return value;
});
const okResult = await load(true).finally(() => {
cleaned += 1;
});

Interactive Tools for This Topic

FAQ

How does the snippet fail?
The code throws `Error` — the guard `!ok` rejects bad states before the main logic runs. Handle it at the call site or let it propagate deliberately.
What does Promise finally Runs Cleanup On Both Paths print when run?
No setup needed: run the file and look for labeled lines like `ok:`, `err:`, `passthrough:` in the output.