1. What is Promise

First, Promise is a class that was created to solve the asynchrony problem, the demon pyramid, and the concurrency asynchrony problem.

An executor is passed in the Promise class. This executor executes immediately by default, and a Promise provides resolve and reject methods that change the state of the Promise. The resolve call triggers successful content transfer, and the reject call triggers failure cause.

2. Three states of Promise

This is a big pity. Promise has three states: pending, successful and rejected. When a Promise is in a waiting state, it can change into a successful state or a failed state. After it changes into a successful state or a failed state, the state of the Promise cannot be changed. There are two calls to reject and to throw exceptions that fail.

3. Then method of Promise

This is a big pity. Each Promise instance will have a THEN method, which contains two functions (onfulfilled and onRejected).

4. Write simple promises

const PENDING = 'PENDING'; const RESOLVED = 'RESOLVED'; // const REJECTED = 'REJECTED'; Class Promise{constructor(executor){this.status = PENDING; // This. Value = undefined; // Success content this.reason = undefined; This.onresolvedcallbacks = []; // Store the successful callback function this.onRejectedCallbacks = []; Resolve = (value) => {if(this.status === PENDING){this.value = value; this.status = RESOLVED; / / need to make successful methods, in turn, performs this. OnResolvedCallbacks. ForEach (fn = > fn ()); }}; let reject = (reason) => { if(this.status === PENDING){ this.reason = reason; this.status = REJECTED; / / need to let the failure of the method in sequence enclosing onRejectedCallbacks. ForEach (fn = > fn ()); }} try{executor(resolve, reject)}catch(e){reject(e) {reject(e)}}; then(onfulfilled, onrejected){ if(this.status === RESOLVED){ onfulfilled(this.value); }; if(this.status == REJECTED){ onrejected(this.reason); }; // When status is pending, Inside the executor must be asynchronous logic / / release subscription model is used to implement the asynchronous logic if (this. The status = = = PENDING) {this. OnResolvedCallbacks. Push (() = > { onfulfilled(this.value); }); this.onRejectedCallbacks.push(()=>{ onrejected(this.reason); }) } }} module.exports = Promise;Copy the code