finally
- Node.js course
- Beginner
- Lesson 92/116
- 5 min
Learn cleanup with .finally.
What is finally?
finally is a method you attach to a Promise chain that runs no matter whether the chain fulfilled or rejected. It is mostly used for cleanup: closing a file, hiding a loading spinner, or releasing a connection.
p
.then(value => console.log(value))
.catch(err => console.error(err))
.finally(() => console.log("done"));Important: the finally callback takes no parameter and its return value does not change the previous Promise's result. Even after an error is caught, finally still runs; but if you throw a new error inside finally, the chain rejects again.
Practice Your turn: cleanup with finally
Create a Promise with Promise.resolve("done"). Add .then(value => console.log(value)) to log the result. Add .catch(err => console.error(err)) to catch any error. Add .finally(() => console.log("cleanup")) to log a final message.
Starter code
// Start with Promise.resolve
// Add .then, .catch and .finallySample solution
Promise.resolve("done")
.then(value => console.log(value))
.catch(err => console.error(err))
.finally(() => console.log("cleanup"));Expected output
done cleanup
finally does not change the value
finally does not change the previous Promise's result; it is only for side effects. Unlike then or catch, it takes no parameter. The value returned from finally is not passed to the next then; the chain keeps its original value.
Promise.resolve(1)
.finally(() => 2)
.then(v => console.log(v)); // 1Here even though finally returns 2, then receives 1. A thrown error or a rejected Promise inside finally rejects the chain; take care not to introduce errors during cleanup.
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Fill in the blank: add finally
p
.then(value => console.log(value))
.____(() => console.log("done"));
p
.then(value => console.log(value))
.finally(() => console.log("done"));
Explanation: finally runs in every case.
2 When does finally run in a Promise chain?
- Only when fulfilled
- Only when rejected
- In both cases Correct answer
- Only when an error is thrown
Explanation: finally runs whatever the outcome.
3 finally properties
| Term | Meaning |
|---|---|
finally |
always runs |
parameter |
takes none |
value |
unchanged |