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 ifpromise
is fulfilled.catch’s
callback is only executed ifpromise
is rejected. Or ifthen’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