The content of the article

Analyze the official documentation to understand the use of promises, the mechanisms behind them, and the problems they solve.

As a result of this trend, most articles about promises on the Web start with a handwritten promise, along with a few complicated promises: “callback hell,” “return value through,” “deferred binding callback,” along with the concepts of microtasks, macrotasks, and so on. There is no mention of standard documentation, or even a passing reference.

I think, based on my experience moving bricks. The most correct way to learn about a technology or feature is to read its official documentation. Do I want to understand vue, I should be able to write vue by hand first??

After the translation of the following Promise/A+ Chinese translation (juejin. Cn), let’s take A look at the analysis of the specification.

My interpretation of Promise/A+

The key concepts of Promise/A+ are as follows:

1. promise There are three states

Pormise must be one of the three states: Pending, depressing, and Rejected.

  • When a promise is in pending state:

    1. You can convert tofulfilledrejectedState.
  • When the promise is fulfilled:

    1. Cannot transition to another state.
    2. There has to be onevalue“And cannot be changed.
  • When the promise is in the Rejected state:

    1. Cannot transition to another state.
    2. There must bereason“And cannot be changed.

About 2.promisethenableThe relationship between

Defines thethenThe object or function of a method is calledthenableobject

So promise is also a Thenable object

So why the concept of Thenable? I guess it’s for compatibility reasons.

We can see that in the Promise Resolution Procedure method, thenable can be accepted as a parameter, which is very flexible.

(3) is the corethenmethods

The THEN method is simple and elegantly defines callbacks.

Let’s look at what the then method does:

  1. Define different state callbacks.

    As documented, a promise represents the end result of an asynchronous operation. So depending on the three different states of this asynchronous operation, we do different things.

    • If in thependingState, do nothing.
    • tofulfilledState, call itthenMethod passed inonfulfilledThe callback.
    • torejectedState, call itthenMethod passed inonRejectedThe callback.

    Callbacks of different states can be added multiple times through the THEN method, as described in the specification. (Delayed binding callback)

  2. Ensure that the callback executes asynchronously.

    The specification explicitly mentions the fulfilled or Rejected callback, which must be performed asynchronously.

    So for javascript as a mechanism of the language, it is obvious to rely on the ability of the host to achieve asynchronous.

    The core is that when the promise state changes to fulfilled or rejected, we cannot call back onFulfilled or onRejected directly at this time. We should use the mechanism provided by the host to save these callbacks in order first. Let the rest of the current code run first and then call it last.

    In professional terms, onFulfilled or onRejected will be called after the current macro task is completed (that is, when only the global execution context is left on the execution context stack). How to implement this mechanism is not specified in the specification.

    Chrome, for example, has a queue of “microtasks” within each “macro task” to store the promise-generated callbacks one by one. Wait until the “macro task” is about to end, in order to call the task in the “micro task”, if another “micro task” is generated at this time, it will be directly thrown into the “micro task” queue, if infinite generation of “micro task”, then this “macro task” will be infinite execution.

  3. Ensure asynchronous sequential execution.

    First, the canonical THEN method must return a new promise, whose state changes with the state of the previous promise. This feature guarantees the order in which callbacks are executed. (Chain call)

    In order to facilitate the use, it is also stipulated that if the onfulfilled promise is not a function, onRejected. Also, make the latter promise accept the state and value of the former promise directly. (Return value through)

    That is, a macro task ——> corresponds to a microtask queue.

So based on the above three points. You should be able to understand the lofty nouns we often see when we talk about promises:

  1. Deferred binding callback

  2. Chain call, return value penetration

That’s the essence.

A bit of enlightenment

  1. promiseIt hasn’t changedjavascirptAny feature of the language. He could have used itjavascirptDo it yourself. That’s why so many people write by hand, rightpromiseIn the article.
  2. According to point 1,promiseThe asynchrony capability is provided by the host. Chrome, for example, provides itMicrotask queue.
  3. onFulfilledoronRejectedWhen triggered, it is not called back immediately. Instead, it is placed on the microtask queue and called sequentially after the synchronous code has finished executing. In other words,promiseresolvedBefore handonFulfilledAnd put it into the microtask queue for execution.

conclusion

The essence of a promise is to normalize an object that represents an asynchronous state. It also uses a then method to delay the binding of callback, cleverly avoiding callback nesting and solving callback hell.

In the last article we translated the Promise/A+ specification,

In this article, we have analyzed and interpreted it.

In the next article we will take A look at the ECMAScript® 2022 Language Specification (TC39.es) extensions based on the Promise/A+ Specification and see how chorme is implemented.

Specification document

First paste the Chinese version of my translation

Promise/A+ 英 文翻译 (juejin. Cn)

Here is the official document

Promises/A+ (promisesaplus.com)