JavaScript Reference ยท Promises and Async
Promise.prototype.finally()
Reference for Promise.prototype.finally(): run cleanup code after a promise settles, how it passes results through, and what happens if it throws.
The finally() method registers a function that runs when a promise settles, whether it fulfilled or rejected. It is meant for cleanup that must happen either way: hiding a loading spinner, closing a connection, releasing a lock.
The callback receives no arguments, because it does not know which outcome happened. The result of the original promise passes straight through to the next step, unless the callback throws or returns a rejected promise.
showSpinner(); loadData() .then(render) .catch(showError) .finally(hideSpinner);
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
promise.finally(onFinally)
| Name | Description |
|---|---|
onFinally |
Called with no arguments once the promise settles. |
Return value: a new promise that settles like the original, after onFinally (and any promise it returns) has completed. If onFinally throws or returns a rejected promise, the new promise rejects with that error instead.
Exceptions: none directly. If onFinally is not a function, it is passed through like then(onFinally, onFinally) would, so it has no effect.
Usage notes
- No access to the value. Use
then()orcatch()when you need the result or the error. - Return values are ignored. Unlike
then(),finally(() => 5)does not change the result. Only throwing, or returning a rejected promise, does. - Waits for returned promises. Asynchronous cleanup, such as closing a file, delays the next step.
- Put it last so it runs after the other handlers have had their turn.
- With
await, the same job is done by afinallyblock intry...catch...finally. - Not a place for logic. Keep it for cleanup, so that the outcome is decided by
then()andcatch().
Browser support
Supported in current versions of all major browsers and Node.js.
Related
- Promise, then(), catch()
- async and await
- Lesson: Promises