Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

Promise.finally() explained in JavaScript

31 What finally on a promise can and cannot change

fair

Work out exactly what .finally() is allowed to do to a chain. Show that the value passes through it untouched, that its own return value is discarded, that a throw inside it replaces the outcome — and that a promise returned from it still delays everybody.

Stuck? Three hints, smallest first
  1. 1. finally is handed no arguments at all, so it cannot even see whether it is on the success or the failure path.
  2. 2. Returning a value from it changes nothing. Throwing from it changes everything.
  3. 3. To catch it delaying the chain, return a promise you control and check that nobody downstream has run yet.

The answer

const order = [];
let release;
const slowCleanup = new Promise((resolve) => { release = resolve; });

let sawArguments = -1;
const passedThrough = await Promise.resolve('₦2,500 paid').finally((...args) => {
  sawArguments = args.length;                  // nothing is passed in
  return 'this return value is thrown away';   // and nothing comes out
});

let cleanups = 0;
const rejectionSurvives = await Promise.reject(new Error('till 2 offline'))
  .finally(() => { cleanups++; })
  .catch((err) => err.message);
await Promise.resolve('ok').finally(() => { cleanups++; });

const throwWins = await Promise.resolve('would have been kept')
  .finally(() => { throw new Error('cleanup itself failed'); })
  .catch((err) => err.message);

const originalBuried = await Promise.reject(new Error('the real problem'))
  .finally(() => { throw new Error('cleanup itself failed'); })
  .catch((err) => err.message);

// A promise returned from finally IS waited for, even though its value is dropped.
const delayed = Promise.resolve('receipt LAG-0031')
  .finally(() => slowCleanup.then(() => order.push('cleanup finished')));
delayed.then((value) => order.push('caller got ' + value));
for (let i = 0; i < 6; i++) await Promise.resolve();
const beforeRelease = order.slice();
release();
await delayed;
for (let i = 0; i < 4; i++) await Promise.resolve();

console.log('through   :', passedThrough, '- arguments seen:', sawArguments);
console.log('rejection :', rejectionSurvives, '- cleanups run:', cleanups);
console.log('a throw   :', throwWins, '/', originalBuried);
console.log('order     :', beforeRelease, '->', order);

Output


      
8 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('the value passes straight through finally', passedThrough, '₦2,500 paid');
test('which is called with no arguments at all', sawArguments, 0);
test('it runs on the failure path too, and the rejection carries on', rejectionSurvives, 'till 2 offline');
test('so both paths ran their cleanup', cleanups, 2);
test('a throw inside finally replaces a perfectly good value', throwWins, 'cleanup itself failed');
test('and buries the original reason, which is now unreachable', originalBuried, 'cleanup itself failed');
test('a promise returned from finally holds the chain up', beforeRelease, []);
test('so the caller is served only once the cleanup has finished', order, ['cleanup finished', 'caller got receipt LAG-0031']);

finally is deliberately blind. It gets no arguments, so it cannot tell success from failure, and its return value is discarded, so it cannot decide the outcome. That is the whole design: it is for releasing things, not for handling them. If you find yourself wanting to know which way it went, you wanted then(onOk, onErr).

The two assertions about throwing are the trap. A finally that fails does not merely fail — it overwrites whatever was there. The sixth is the bad one: a real failure came in, the cleanup threw on the way out, and the original reason is now gone from the chain entirely, with no cause linking them. Cleanup code that can throw belongs in its own try, or wrapped so it reports rather than replaces.

The last pair is the part people do not expect. Returning a value from finally is ignored, but returning a promise is not: the chain waits for it and only then passes the original value on. Useful when the cleanup must complete first — closing a transaction before the caller reads a total. Expensive when it was an accident, because an async cleanup function returns a promise whether you meant it to or not, and every caller now waits for it.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.