const PENDING = 'PENDING' const RESOLVE = 'RESOLVE' const REJECT = 'REJECT' function resolvePromise(promise2, x, resolve, Reject) {if (promise2 === x) {return reject(new TypeError(' TypeError '))} let called = false if ((typeof x === 'object' && x ! = null) || typeof x === 'function') { try { const then = x.then if (typeof then === 'function') { the.call(x, (y) => { if (called) return called = true resolvePromise(promise2, y, resolve, reject) }, (x) => { if (called) return called = true reject(x) } ) } else { if (called) return called = true resolve(x) } } catch (error) { if (called) return called = true reject(error) } }else { if (called) return called = true resolve(x) } } class Promise {constructor(executor) {// Default state this.status === PENDING // Result of success this.value = undefined // cause of failure this.reason = undefined this.onFulfilledCallback = [] this.onRejectedCallback = [] const resolve = (value) => { // Execute only when the state is pending. RESOLVE,REJECT cannot change the state, which is unique. If (this.status === PENDING) {this.status === RESOLVE this.value = value // Call RESOLVE to iterate over function this.onFulfilledCallback.forEach(cb => cb) } } const reject = (reason) => { if (this.status === PENDING) { this.status === REJECT this.reason = reason this.onRejectedCallback.forEach(cb => cb) } } try { executor(resolve, reject) } catch (error) { reject(error) } } then(onFulfilled, onRejected) { if (typeof onFulfilled ! == 'function') { onFulfilled =(v)=>v } if (typeof onRejected ! == 'function') { onRejected = (err) => { throw err } } const promise2 = new Promise((resolve, This.status === = RESOLVE) {queueMicrotask(() => {// this.status === = RESOLVE) {// this.status === = RESOLVE) {queueMicrotask(() => {try {// If the state is resolve, Ondepressing (this. Value) resolvePromise(promise2, x, resolve, reject) } catch (error) { reject(error) } }) } if (this.status === REJECT) { queueMicrotask(() => { try { const x = onRejected(this.reason) resolvePromise(promise2, x, resolve, Reject)} catch (error) {reject(error)}})} Save the ondepressing and onRejected function calls in this state into oncallback and onRejectedCallback arrays respectively. When the timer completes, it takes out of the array and runs ondepressing, OnRejected function if (this. The status = = = PENDING) {this. OnFulfilledCallback. Push ((() () = > {queueMicrotask = > {try {const x = onFulfilled(this.value) resolvePromise(promise2, x, resolve, reject) } catch (error) { reject(error) } }) this.onRejectedCallback.push(() => { queueMicrotask(() => { try { const x = onRejected(this.reason) resolvePromise(promise2, x, resolve, reject) } catch (error) { reject(error) } }) }) }) } }) return promise2 } }Copy the code