Jordan Harband Promise is proposed. The prototype. Finally this section of the proposal.

How does it work?

.finally() is used like this:

Promise. Then (result = > {...}). The catch (error = > {...}), finally (() = > {...});Copy the code

Finally callback is always executed. For comparison:

  • The callback of then will only be performed when the promise is fulfilled.
  • A callback to a catch is executed only if the Promise throws an exception for the Rejected or then callback, or if it returns a Rejected Promise. In other words, the following code snippet:
Promise.finally (() => {«statements»});Copy the code

Is equivalent to:

Promise. then(result => {«statements»returnresult; }, error => {«statements» throw error; });Copy the code

Use case

The most common use case is something like a synchronized finally clause: do some cleanup after processing a resource. Error or no error, this kind of work is necessary. Here’s an 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(); });Copy the code

.finally() is similar to finally {} in synchronized code

In synchronized code, a try statement is divided into three parts: a try clause, a catch clause, and a finally clause. Compare the Promise:

  • The try clause is equivalent to calling a promise-based function or.then() method
  • The catch clause is equivalent to the.catch() method of Promise
  • Finally clauses are equivalent to the.finally() method the proposal introduced in Promise

However, finally {} can return and throw. In a.finally() callback, only throw. Return does nothing. This is because this method cannot distinguish between an explicit return and a normally terminated callback.

availability

  • NPM package promise. Prototype. The finally is. Finally a polyfill ()
  • V8 5.8+ (e.g. Node.js 8.1.4+) : Available with the –harmony-promise-finally flag. (Learn more)

Further reading

  • Promises for asynchronous programming

Original: http://exploringjs.com/es2018-es2019/ch_promise-prototype-finally.html