HomeWeb WorldJavaScriptUnderstanding Promise.prototype.finally()

Understanding Promise.prototype.finally()

Understanding Promise Prototype Finally

#How Does Promise.prototype.finally works

.finally()Ā works as follows:

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

finallyā€™s callback is always executed. Compare:

  • thenā€™s callback is only executed ifĀ promiseĀ is fulfilled.
  • catchā€™s callback is only executed ifĀ promiseĀ is rejected. Or ifĀ thenā€™s callback throws an exception or returns a rejected Promise.

In other words: Take the following piece of code.

promise
.finally(() => {
    Ā«statementsĀ»
});

This piece of code is equivalent to:

promise
.then(
    result => {
        Ā«statementsĀ»
        return result;
    },
    error => {
        Ā«statementsĀ»
        throw error;
    }
);

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;
db.open()
.then(conn => {
    connection = conn;
    return connection.select({ name: 'Jane' });
})
.then(result => {
    // Process result
    // Use `connection` to make more queries
})
Ā·Ā·Ā·
.catch(error => {
    // handle errors
})
.finally(() => {
    connection.close();
});

.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:

  • TheĀ tryĀ clause very loosely corresponds to invoking a Promise-based function or callingĀ .then().
  • TheĀ catchĀ clause corresponds to theĀ .catch()Ā method of Promises.
  • TheĀ finallyĀ clause corresponds to the new Promise methodĀ .finally()Ā introduced by the proposal.

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.

Availability

Further reading

Source Viva:Ā http://2ality.com/2017/07/promise-prototype-finally.html

RELATED ARTICLES

Most Popular