This article is written with strict reference to the latest official documentation, ensuring that all terms, key codes, and variable names are from official documentation.

Specification document

Post the official document first.

Promises/A+ (promisesaplus.com)

Promises/A+

Typesetting safety according to official documents, literal translation to ensure accuracy. (That is, the terms promise, then, value, reason, pending, depressing and Rejected will not be forcefully translated).

On why literal translation: because I believe that standard documents must have rigor and accuracy. Free translation, easy to introduce the translator’s understanding bias. Of course, reading the original text is the most authentic, therefore, I suggest reading the original text, the translation of this article is only for auxiliary.


Translation Text:

An open, robust, and universal JavaScript Promise standard. Developed by developers for their reference.

A promise represents the end result of an asynchronous operation. The primary way to interact with a promise is through its method, then. This method obtains the final value of the promise by registering callback, or the reason why the promise cannot be fulfilled.

The specification details the behavior of the THEN method and provides an interoperable foundation on which all Promises that comply with Promises/A+ can rely. Although Promises/A+ organizations may occasionally modify this specification with minor backward compatible changes to address newly discovered situations, we will only make major or backward incompatible changes after careful consideration, discussion, and testing. Therefore, the specification should be considered very stable.

Promises/A+ : Promises/A+ : Promises/A+ : Promises/A+ : Promises/A+ : Promises/A+ : Promises/A+ : Promises/A+ : Promises/A+ : Promises/A+ : Promises/A+ : Promises/A+ : Promises/A+ : Promises/A+ : Promises/A+ : Promises/A+

Finally, the core of Promises/A+ norms does not include: how to create, reject or reject Promises. Instead, you choose to focus on providing interoperable THEN methods. However, future work accompanying the specification may address these topics. Promises/A+ : Promises/A+ : Promises/A+ : Promises/A+ : Promises/A+

1. The term

  1. A “prmoise” is an object or function that has then methods that conform to this specification.

  2. “Thenable” is an object or function that defines the then method.

  3. “Value” is any valid JavaScript value (including undefined, thenable, and promise).

  4. “Exception” is a value thrown by a throw statement.

  5. “Reason” is a value indicating that the promise is rejected.

2. Request

  1. The state of the promise

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

    1. When a promise is in pending state:

      1. You can switch to the fulfilled or Rejected state.
    2. When the promise is fulfilled:

      1. Cannot transition to another state.
      2. There must be a value and it cannot be changed.
    3. When the promise is in the Rejected state:

      1. Cannot transition to another state.
      2. There must be reason and it cannot be changed.
  2. Then method

    A promise must provide a then method that accesses the current or final value or Reason. (Late binding callback)

    Pormise’s then method takes two parameters

    promise.then(onFulfilled, onRejected)

    1. OnFulfilled and onRejected are both optional parameters.

      1. ifonFulfilledIf not a function, ignore it.
      2. ifonRejectedIf not a function, ignore it.
    2. If ondepressing is a function:

      1. It must be inpromisefulfilledLater, in order topromisevalueAs the first argument, call.
      2. It can’t be inpromisefulfilledCall before.
      3. It cannot be called more than once.
    3. If onRejected is a function:

      1. It must be inpromiserejectedLater, in order topromisereasonAs the first argument, call.
      2. It can’t be inpromiserejectedCall before.
      3. It cannot be called more than once.
    4. OnFulfilled or onRejected cannot be called until the execution Context stack contains only the platform code [3.1].

    5. Ondepressing or onRejected must be called in the form of a function (i.e. can’t have this value) [3.2]

    6. The then method can be called multiple times by the same promise.

      1. If or whenpromiseIn afulfilledStates, all of their ownonFulfilledThe callback function must be followedthenThe order of registration is called.
      2. If or whenpromiseIn arejectedStates, all of their ownonRejectedThe callback function must be followedthenThe order of registration is called.
    7. The then method must return a promise[3.3]

      promise2 = promise1.then(onFulfilled, onRejected);

      1. ifonFulfilledoronRejectedReturn a valuex, the implementationPromise Resolution Procedure.
      2. ifonFulfilledoronRejectedAn exception is thrownepromise2Have to beeAs reason, go to the Rejected state.
      3. ifonFulfilledIt’s not a function, andpromise1Is in a depressing state, thenpromise2Must be withpromise1The same value is fulfilled. (Translator’s note: The value penetrates)
      4. ifonRejectedIt’s not a function, andpromise1If the rejected state is in the rejected statepromise2Must be withpromise1The same reason is rejected. (Translator’s note: The value penetrates)
  3. Promise Resolution Procedure

    The Promise Resolution Procedure is an abstract operation. It takes a promise and a value as input, which we call: [[Resolve]](promise, x). If x is a Thenable, it will try to make the Promise the same state as X, provided x is a similar Promise object. Otherwise, it will make the promise move to a fulfilled state with x as value.

    This thenables treatment allows different Promises to interoperate as long as they expose A THEN method that complies with Promises/A+. It also allows Promises/A+ implementations to “assimilate” inconsistent implementations using sound THEN methods.

    [[Resolve]](promise, x) Do the following:

    1. If the promise and X reference the same object, a TypeError is used as reason to make ‘promis’ rejeted.

    2. If x is also a Promise, let the promise accept its state [3.4]:

      1. ifxIs in a pending state,promiseMust remain pending untilxThis will become a pity or rejected state.promiseSynchronously change.
      2. If or whenxThis is a big pity. I will gradually forget the song with the same valuepromiseThis will become a depressing state.
      3. If or whenxIn the rejected state, use the same reasonpromiseIt’s also the Rejected state.
    3. If x is an object or a function.

      1. Let then equal x.teng. [3.5]

      2. If x. Chen is read and raises an exception e, use eas reason to change the Promise state to Rejected.

      3. If then is a function, call it with x as this, passing in the first argument resolvePromise and the second argument rejectPromise.

        1. If resolvePromise is called in y, execute [[Resolve]](promise, y)

        2. If rejectedPromise is called by r, use r as reason to change the promise state to Rejected

        3. If both resolvePromise and rejectPromise are called, or more than once. Only the first call is valid, the rest is ignored.

        4. If the call to THEN throws an exception e,

          1. ifresolvepromiserejectPromiseIf it has already been called, ignore it.
          2. Otherwise, in order toeAs a reason to letpromiseChange to the Rejected state.
      4. If then is not a function, use x as value to make the promise become a fulfilled state.

    4. If x is not an object or function, use x as value to make the promise become a fulfilled state.

If a promise is resolved by an object in a loop thenable chain and the recursive nature of [[Resolve]](promise, thenable) causes it to be called again, it will be stuck in infinite recursion according to the algorithm above. While not mandatory, the algorithm encourages implementers to detect the presence of such recursions and reject promises as a reason with TypeError [3.6].

3. Note

  • Note 1 The platform code here refers to the engine, environment, and promise implementation code. In practice, ensure that the onFulfilled and onRejected methods are executed asynchronously and should be executed in a new execution stack after the event loop in which the THEN method is called. This event queue can be implemented using a “macro-task” mechanism or a “micro-task” mechanism. Because the promise implementation code is itself platform code, the code itself may already contain a task scheduling queue when processing the handler.

    The two categories are classified as follows:

    • macro-task:Script (whole code)setTimeout.setInterval.setImmediate, I/O, UI rendering
    • micro-task: process.nextTick.Promises(native promises implemented by browsers),Object.observe.MutationObserver

    See StackOverflow for answers

  • Note 2: in strict mode **, the value of this is undefined; In non-strict mode it is a global object.

  • Note 3 Code implementations can allow promisE2 === PROMISe1 if all requirements are met. Each implementation should document whether and under what conditions it allows PROMISE2 === PROMISe1.

  • Note 4 In general, x is considered a true promise if it conforms to the current implementation. This rule allows those exceptions to accept Promises that meet known requirements.

  • Note 5 In this step, we first store a reference to x.teng, and then test and call the reference to avoid multiple access to the x.teng property. This precaution ensures that the property is consistent because its value can be changed during retrieval calls.

  • Note 6 Implementations should not impose a limit on the depth of the Thenable chain and assume that recursion beyond this limit is an infinite loop. Only true loop recursion should result in TypeError exceptions; If the Thenable is different across an infinite chain, recursion is always the correct behavior.