This is the 27th day of my participation in the August More Text Challenge.

preface

Description of content

  • Promises/A + specification
  • Make a Promise
  • Asynchronous JavaScript programming

Promises/A + specification

Promise preface

  • Promises represent the end result of asynchronous operations, and we interact with them through the then method
  • The then method registers a callback function to accept the result of a promise’s execution, or the reason it didn’t
  • This specification details the behavior of then methods and provides a basis for interactive operations. This specification is very stable, except for super bugs that cannot be tolerated.
  • This specification focuses on then methods. It does not deal with how to create, implement, or reject promises. It focuses on providing methods for interactive operations.

1. The term

  • promise

  • Is an object or function that has then methods (used to implement this specification)

  • thenable

  • Is an object or function that defines the then method

  • value

  • Is a valid, arbitrary JavaScript value (including undefined, thenable, promise)

  • exception

  • Is a value thrown using a throw statement

  • reason

  • Is a value used to indicate the reason for rejecting a promise

2. Request

Promise States: a Promise must be one of three States: pending, fulfilled, rejected.

  • When the state is pending

  • State can become a pity or reject

  • When the state is fulfilled

  • State cannot be converted

  • The promise must have a value that cannot be changed

  • When the state is rejected

  • State cannot be converted

  • The promise must have a reason, and the value cannot be changed

Then methods: A promise must provide then methods to retrieve the promise’s value or reason

Then method must accept two parameters,promise. Then (onFulfilled,onRejected)

  • Ondepressing and onRejected are both optional parameters. If they are not functions, they must be ignored.

  • This is a pity when onFulfilled,onRejected is a function

  • Ondepressing must be called after the promise state becomes depressing, and the promise value is the first parameter of ondepressing. When the state becomes depressing, ondepressing cannot be called again

  • OnRejected must be called after the state of the promise changes to Rejected. The reason of the promise is the first parameter of onRejected. When the state changes to Rejected, onRejected cannot be called again

  • OnFulfilled,onRejected can only be called once at most

  • Ondepressing,onRejected cannot be called until the execution context of the stack contains only platform code

  • OnFulfilled,onRejected must be called as a function. (No this value)

  • The THEN method can be called multiple times by a promise

  • When the promise is filfilled, all onFulfilled callback functions must be executed in the order in which they are declared

  • When a promise is Rejected, all onRejected callback functions must be executed in the order in which they are declared

  • The then method must return a promise, such as promise2 = promise1. Then (onFulfilled, onRejected);

  • `

    if

    OnFulfilled or onRejected returns an X, then run the promise step [[Resolve]](promise2, x) ‘

  • If onFulfilled or onRejected throws exception E, the state of promise2 must be fulfilled and the value must be the same as promise1

  • If ondepressing is not a function and the state of promise1 is a pity, the state of promise2 must be a pity and its value must be the same as that of promise1

  • If onRejected is not a function and the state of promise1 is Rejected, the state of promise2 must be Rejected and the reason must be the same as that of promise1

3. Promise solution steps

The Promise Resolution Procedure is an abstract operation that inputs a promise and a value, which we describe as [[Resolve]](promise, x).

  • If a Promise and X reference the same object, the Promise is rejected on TypeError grounds.

  • If x is a Promise, its state is adopted:

  • If X is waiting, the promise must remain in the wait state until x is completed or rejected. [1]

  • If x completes, the promise completes with the same value. [2]

  • If X has rejected, Promise rejects for the same reason. [3] (The state of.then() depends on the state of the returned promise)

  • Otherwise, if x is an object or function (less common)

  • Run x. Chen.

  • If e is the result of an exception thrown when the median value of x. teng is taken, reject the promise with e as the reason.

  • If then is a function, call this with x as this and resolvePromise as the first argument and rejectPromise as the second argument, where:

  • If resolvePromise calls y as a value, run [[Resolve]](promise, y).

  • If the rejectPromise invokes R as the reason, reject the promise with R as the reason.

  • If both resolvePromise and rejectPromise are called, or if multiple calls are made to the same parameter, the first call takes precedence and any other calls are ignored.

  • If calling then raises exception E,

  • If a resolvePromise or rejectPromise has already been invoked, it is ignored.

  • Otherwise, reject the promise with e as the reason.

  • If then is not a function, the promise call to X becomes completed.

  • If x is not an object or function, promise calls x to the completed state (common).

If a promise is resolved using thenable in a loop chain, [[Resolve]](promise, thenable) will cause recursion, and [[Resolve]](promise, thenable) will be called again, causing infinite recursion. It is recommended (but not required) to detect such recursion and reject promises on TypeError grounds.

I know how long ECMAScript is, so my first reaction to Promises/A+ is really short. It can be used as an English essay to practice, after all, the ability to read English documents is necessary.

Promise to realize

The train of thought that realizes here is main in these several respects

  • Private property

  • State can only be ‘pending’,’resolved’,’rejected’

  • value

  • reason

  • Execute executor(resolve,reject)

  • Provide the resolve method

  • Provide reject method

  • The onFulfilled function will be implemented only when the state of the Promise changes. Here two arrays will be used to store the onFulfilled function passed in by the THEN method, and the onRejected function will be implemented sequentially. (Add code to relove and Reject implementations)

  • Chain calls, in the then method

  • Create promise2 (declare an executor of promise2 here, taking the state of promise1 into account)

  • Modify the state of promise2 based on the results of the current promise.

  • Return promise2

  • How to place the then method’s callback function into the microtask via queueMicrotask, refer to MDN

Summary of main points:

  • The then method executes immediately and returns a brand new Promise object

  • As a chain call, the former promise1 calls the then method to generate the new promisE2

  • Ondepressing, onFulfilled (); onfulfilled (); onfulfilled ();

  • Call the THEN method when the current state of promise1 is pending

  • Don’t think about chain call: the callback onfulfilled, onRejected into onResolvedCallbacks respectively, onRejectedCallbacks stack

  • Consider the chain invocation: Perform ondepressing and onRejected callback when the promise1 state changes, and change the state of promise2, that is, perform the promise’s resolve and reject

  • So here in onResolvedCallbacks onRejectedCallbacks stack of function will be some complicated, he needs to hold promise1 values change, and change the state of promise2

  • Call the THEN method, and the current state of promise1 is depressing

  • This will be a big pity. Then directly implement the onfulfilled into the micro-task, which will be automatically implemented by the micro-task

  • Call the THEN method when the state of promise1 is Rejected

  • Put the onRejected callback into the micro task and let the micro task execute it automatically

Complex reasons for promises:

  • When you are used to thinking according to the non-chain call, you go to see the version of the chain call is very outrageous, recommended to learn the chain call directly. Because you can generalize from a three-dimensional world to a two-dimensional plane, but you can’t imagine a three-dimensional world from a two-dimensional plane.
  • Tasks are divided into tasks currently performed by the main thread, tasks performed by other threads, and tasks to be performed by the main thread in the future. Use callbacks, resolve, reject, to notify the main thread when other threads have finished. (Again, the essence of the confusion here is not who executes it, but the order in which it is executed.)
  • Through the then method, there are old and new promises, both of which have the same properties and interact with each other. Similar names tend to get entangled in themselves, and many logic will be misplaced if one detail is not paid attention to, just like a puzzle

It is highly recommended

Juejin. Cn/post / 699796…

Github.com/isboyjc/pro…

Promise task scheduler for interview questions

Requirements:

Implement an asynchronous scheduler function that continuously adds asynchronously executed functions, but it can only execute up to three asynchronous functions at a time and return the results.

Use the Promise version

Class Scheduler {list = []; Count = 0; Constructor (num) {this.num = num; } async add(fn) {// If count>=num, the current task is to be executed in the future Then place resolve in a memory space accessible to the current performer and wait for it to be invoked. this.count >= this.num ? await new Promise((resolve) => { this.list.push(resolve) }) : ""; this.count++; const result = await fn(); this.count--; if (this.list.length > 0) { this.list.shift()(); } return result; }}Copy the code

Don’t think about who’s going to do it, just think about if it can be done, if it can be done, if it can’t, and when it can be done.

Why not think about who’s going to do it? Because in this case, it doesn’t matter who’s doing it in this context.

The real soul here is async await, imagine what you would do if you didn’t have async await. I’m going to put a pit in here and decompose it next time.

PS: A day full of dry goods, August essay is coming to an end, I have been afraid before, afraid of early too hard, afraid that I can not adhere to the last. Look now, oneself still have some spare power, hey hey. Go all out this weekend! Want to see now their own limit to what point, with no regret in the heart of the faith began to sprint, as for the end where, who knows.