JavaScript
Clean up asynchronous work with finally
Use finally for cleanup that must run after an awaited operation succeeds or fails. Keep the original error visible by avoiding a return or replacement error inside the cleanup block.
Worked example
Node.js example · save as example.mjs and run node example.mjs
let busy = false;
async function run() {
busy = true;
try {
throw new Error("Task failed");
} finally {
busy = false;
}
}
try { await run(); } catch (error) { console.log(error.message); }
console.log(busy);How it works
The finally block runs while the exception propagates to the caller. This restores the busy flag even though the task failed. The same structure can close a resource or restore a UI state after an asynchronous operation.
Limits and mistakes
Cleanup can itself fail and obscure the original error. Decide how to report that second failure for important resources. A return statement inside finally overrides the try block’s return or exception, which is usually an unintended control-flow change.
Check the result
Expect Task failed and false. Replace the failure with a successful return and confirm the cleanup still runs. Check that the caller receives the original error on failure.
Sources
Reference documentation for the behavior used in this guide: