Skip to content

Promise.prototype.finally(): clean up once (ES2018)

  • How promise.finally(callback) runs clean-up after success and failure.
  • Why the callback receives no arguments and why its return value is usually ignored.
  • When finally does change the outcome: a throw or a rejected promise.
  • How it differs from .then(f, f) and from try...finally with await.

TL;DR: promise.finally(onFinally) calls onFinally with no arguments once promise settles, then returns a promise that settles the same way as the original: same value or same rejection reason. The only exceptions are when onFinally throws or returns a rejected promise, which replaces the outcome, and when it returns a pending promise, which delays it.

It was added in ECMAScript 2018 and is supported by every current browser and server runtime (details in Compatibility).

Some work must happen however an operation ends: hide a loading spinner, release a lock or a pooled connection, stop a timer, close a file. With only then and catch, the clean-up has to be written twice, and the failure path must remember to re-throw.

Running the samples: save each sample as a .mjs file and run it with Node.js 22 (node sample.mjs). The samples use top-level await, and the outputs shown were produced with Node.js 22.23.

Here the OrdersPortal app shows a spinner while it loads orders:

const ui = { spinner: false };
const loadOrders = (fail) =>
new Promise((resolve, reject) =>
setTimeout(() => (fail ? reject(new Error('orders: HTTP 503')) : resolve(['o-1', 'o-2'])), 10));
// Before: the clean-up is duplicated in both handlers.
function showOrdersBefore(fail) {
ui.spinner = true;
return loadOrders(fail).then(
(orders) => { ui.spinner = false; return orders; },
(error) => { ui.spinner = false; throw error; },
);
}
// After: one clean-up callback, and the outcome passes through untouched.
function showOrders(fail) {
ui.spinner = true;
return loadOrders(fail).finally(() => { ui.spinner = false; });
}
console.log(await showOrdersBefore(false), ui.spinner);
console.log(await showOrders(false), ui.spinner);
try {
await showOrders(true);
} catch (error) {
console.log('rejected:', error.message, '| spinner:', ui.spinner);
}

Output:

[ 'o-1', 'o-2' ] false
[ 'o-1', 'o-2' ] false
rejected: orders: HTTP 503 | spinner: false

The “before” version works, but forgetting throw error in the second handler would silently turn a failure into a success with the value undefined. finally removes that trap.

// Fragment: signature
const next = promise.finally(onFinally);
// onFinally is called with no arguments when promise settles.
// next settles like promise, unless onFinally throws or returns a rejected promise.

The rules, all visible in this sample:

  1. The callback receives no arguments. It cannot tell whether the promise fulfilled or rejected; that is deliberate, since clean-up should not depend on it.
  2. A normal return value is ignored. The original value passes through.
  3. A throw, or a returned rejected promise, replaces the outcome with that rejection.
  4. A returned promise is awaited before the original outcome is passed on, so asynchronous clean-up completes first.
  5. finally does not handle a rejection: the original reason is re-thrown and still needs a catch somewhere.
  6. A non-callable argument is passed straight to then, so the outcome passes through unchanged.
// 1. The callback gets no arguments.
await Promise.resolve('o-1').finally((...args) => console.log('args:', args.length));
// 2. A normal return value is ignored: the original value passes through.
console.log(await Promise.resolve('o-1').finally(() => 'ignored'));
// 3. Throwing (or returning a rejected promise) replaces the outcome.
try {
await Promise.resolve('o-1').finally(() => { throw new Error('audit log failed'); });
} catch (error) {
console.log('replaced by:', error.message);
}
// 4. A returned promise is awaited before the original outcome is passed on.
const start = Date.now();
const value = await Promise.resolve('o-1').finally(() => new Promise((r) => setTimeout(r, 50)));
console.log(value, Date.now() - start >= 45 ? 'waited ~50 ms' : 'did not wait');
// 5. finally does not handle a rejection: it re-throws the original reason.
try {
await Promise.reject(new Error('orders: HTTP 503')).finally(() => console.log('cleanup ran'));
} catch (error) {
console.log('still rejected:', error.message);
}
// 6. A non-callable argument is passed straight to then(), so the outcome passes through.
console.log(await Promise.resolve('o-1').finally(undefined));

Output:

args: 0
o-1
replaced by: audit log failed
o-1 waited ~50 ms
cleanup ran
still rejected: orders: HTTP 503
o-1

Under the hood, the specification defines finally in terms of then. It wraps onFinally in two functions: on fulfillment it calls onFinally(), resolves its result, and then returns the original value; on rejection it does the same and then re-throws the original reason. Because it calls this.then(...), finally also works on promise subclasses and inherits their behavior.

// then(f, f) is not the same as finally(f).
const cleanup = () => 'cleanup result';
console.log(await Promise.reject(new Error('boom')).then(cleanup, cleanup)); // swallowed!

Output:

cleanup result

.then(f, f) passes the value or reason to f, and its return value becomes the new result, so a rejection is converted into a success. finally keeps the original outcome.

OrdersPortal limits report exports to two at a time with a small semaphore. Each export must release its slot whether it succeeds or fails; a leaked slot would eventually block every export.

// export-jobs.mjs - OrdersPortal runs report exports with at most 2 in flight.
class Semaphore {
#free;
#waiting = [];
constructor(slots) { this.#free = slots; }
acquire() {
if (this.#free > 0) { this.#free--; return Promise.resolve(); }
return new Promise((resolve) => this.#waiting.push(resolve));
}
release() {
const next = this.#waiting.shift();
if (next) next(); else this.#free++;
}
get free() { return this.#free; }
}
const exportSlots = new Semaphore(2);
function runExport(reportId, buildReport) {
return exportSlots.acquire()
.then(() => buildReport(reportId))
// Runs on success and failure, and keeps the export's own result or error.
.finally(() => {
exportSlots.release();
console.log(`released slot for ${reportId}`);
});
}
const buildReport = (id) =>
new Promise((resolve, reject) =>
setTimeout(() => (id === 'r-2' ? reject(new Error(`${id}: query timed out`)) : resolve(`${id}.csv`)), 10));
const results = await Promise.allSettled(['r-1', 'r-2', 'r-3', 'r-4'].map((id) => runExport(id, buildReport)));
console.log(results.map((r) => (r.status === 'fulfilled' ? r.value : `ERR ${r.reason.message}`)));
console.log('free slots:', exportSlots.free);

Output:

released slot for r-1
released slot for r-2
released slot for r-3
released slot for r-4
[ 'r-1.csv', 'ERR r-2: query timed out', 'r-3.csv', 'r-4.csv' ]
free slots: 2

The failed export r-2 still releases its slot, its error still reaches the caller, and both slots are free at the end. Promise.allSettled collects the mixed results.

Inside an async function, the statement form try...finally does the same job and is often easier to read:

// Fragment: equivalent of runExport with await
async function runExport(reportId, buildReport) {
await exportSlots.acquire();
try {
return await buildReport(reportId);
} finally {
exportSlots.release();
}
}

The await in return await matters here: without it, the finally block runs as soon as the promise is returned, before the export has finished. Prefer .finally() in promise chains and in code that returns a promise without being async; prefer try...finally when the function is already async.

  • Expecting the value in the callback. finally((result) => ...) always receives undefined. If clean-up depends on the outcome, use then/catch.

  • Trying to change the result by returning a value. A normal return is ignored. Transform results in then.

  • Throwing from clean-up. An exception in onFinally replaces the original outcome, including the original error. Keep clean-up simple, or catch and log inside it.

  • Treating finally as error handling. It re-throws. A chain that ends with .finally() and no .catch() still produces an unhandled rejection, which crashes Node.js by default.

    // Fragment: the promise returned by finally() also rejects, and nothing handles it.
    const p = Promise.reject(new Error('orders: HTTP 503'));
    p.finally(() => console.log('cleanup ran'));
    p.catch((e) => console.log('handled on p:', e.message)); // handles p, not the finally() result

    Running it prints both lines and then exits with code 1 on Error: orders: HTTP 503. Put .catch() after .finally() (or await it inside try).

  • Using .then(f, f) as a substitute. It swallows rejections, as shown above.

  • return without await inside try...finally. The clean-up runs before the returned promise settles.

Use finally for outcome-independent clean-up: UI state, locks, semaphores, timers, temporary resources, metrics that record that an operation ended. Do not use it to:

  • Recover from errors. That is catch.
  • Transform the result. That is then.
  • Branch on success or failure. Use then(onFulfilled, onRejected) or catch.
  • Wait for many operations and clean up once. Attach a single finally to the combined promise (for example Promise.allSettled(tasks).finally(done)) rather than one per task.

According to MDN’s browser compatibility data, Promise.prototype.finally is supported in Chrome 63, Edge 18, Firefox 58, Safari 11.1 (iOS Safari 11.3), Node.js 10.0.0, Deno 1.0 and Bun 1.0. Internet Explorer never supported it.

TypeScript: declared in lib.es2018.promise.d.ts as finally(onfinally?: (() => void) | undefined | null): Promise<T>, so the result keeps the original type T. Add es2018 or later to lib if a project pins an older one. For older runtimes, use a maintained polyfill such as core-js.

1. What does finally pass to its callback, and what happens to the callback’s return value? Nothing: it is called with no arguments. A normal return value is ignored and the original value or reason passes through. Only a throw or a rejected promise changes the outcome, and a pending promise delays it.

2. What is the difference between p.finally(f) and p.then(f, f)? then(f, f) gives f the value or reason and uses f’s return value as the new result, so it converts a rejection into a fulfillment. finally(f) calls f without arguments and preserves the original outcome.

3. Why can a chain ending in .finally() still crash a Node.js process? Because finally re-throws the original rejection. The promise it returns rejects, and if nothing handles it, Node.js treats it as an unhandled rejection, which terminates the process by default.

4. Senior scenario: a service leaks database connections under load. Code reviews show pool.acquire().then(conn => conn.query(sql)).then(release). How do you fix it and prevent it recurring? The release is skipped whenever the query rejects. Move release into finally (or try...finally with return await in an async function) so it runs on both paths, and keep the release itself from throwing, since an exception there would replace the query error. To prevent recurrence, wrap the pattern in one helper such as withConnection(fn) that acquires, calls fn, and releases in finally, then forbid raw acquire through a lint rule or code review. Add a metric for pool slots in use so leaks show up before the pool is exhausted.

  • finally (ES2018) runs clean-up after fulfillment or rejection and passes the original outcome through.
  • The callback gets no arguments; its return value is ignored unless it throws, returns a rejected promise, or returns a pending promise.
  • It does not handle errors. Add .catch() after it.
  • .then(f, f) is not equivalent: it swallows rejections.
  • In async functions, try...finally with return await is the statement form of the same idea.
  • Promises: the promise model and then/catch.
  • Async/Await: try...finally in asynchronous functions.
  • Promise.allSettled: collect mixed results, as in the export example.
  • Promise.any: first success wins; its example aborts the slower requests in a finally block.
  • Error handling: try, catch and finally statements.