Exploring ES2018 and ES2019
Please support this book: buy it or donate
(Ad, please don’t block.)

11. Promise.prototype.finally()

This chapter explains the proposal “Promise.prototype.finally” by Jordan Harband.

11.1. How does it work?

.finally() works as follows:

.then(result => {···})
.catch(error => {···})
.finally(() => {···});

finally’s callback is always executed. Compare:

In other words: Take the following piece of code.

.finally(() => {

This piece of code is equivalent to:

    result => {
        return result;
    error => {
        throw error;

11.2. Use case

The most common use case is similar to the most common use case of the synchronous finally clause: cleaning up after you are done with a resource. That should always happen, regardless of whether everything went smoothly or there was an error.

For example:

let connection;
.then(conn => {
    connection = conn;
    return connection.select({ name: 'Jane' });
.then(result => {
    // Process result
    // Use `connection` to make more queries
.catch(error => {
    // handle errors
.finally(() => {

11.3. .finally() is similar to finally {} in synchronous code

In synchronous code, the try statement has three parts: The try clause, the catch clause and the finally clause.

In Promises:

However, where finally {} can return and throw, returning has no effect inside the callback .finally(), only throwing. That’s because the method can’t distinguish between the callback returning explicitly and it finishing without doing so.

11.4. Availability

11.5. Further reading