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
- The npm packageĀ
promise.prototype.finally
Ā is a polyfill forĀ.finally()
. - V8 5.8+ (e.g. in Node.js 8.1.4+): available behind the flagĀ
--harmony-promise-finally
Ā (details).
Further reading
- āPromises for asynchronous programmingā in āExploring ES6ā
Source Viva:Ā http://2ality.com/2017/07/promise-prototype-finally.html