Write A Promise that conforms to the Promise/A+ specification
Promise/A+ Spec Reference This blogger really wrote really well first things we should know: In Promise:
- First we return a Promise object when we call a Promise
- When you build a Promise, you pass it a function argument, Executor, which executes immediately
- Resolve is called when the function succeeds, and Rejected is called if it fails
- The Promise state is irreversible and cannot be stopped. By calling both resolve and reject, the result of the first call is taken by default.
const PENDING = "PENDING"; const FULFILLED = "FULFILLED"; const REJECTED = "REJECTED" class Promise { constructor(executor) { this.status = PENDING; this.value = undefined; this.reason = undefined; This. OnResolvedCallbacks = [] this. OnRejectedCallbacks = [ (value) => { if (this.status === PENDING) { this.status = FULFILLED; this.value = value; This. OnResolvedCallbacks. ForEach (fn = > {fn ()})}} / / failure called function let rejected = (reason) = > {if (this. The status = = = PENDING) { this.status = REJECTED; this.reason = reason; This. OnRejectedCallbacks. ForEach (fn = > {fn ()}) / / need to make successful methods in turn perform}} / / immediate execution executor try {executor (resolved, This is a big pity, once)} catch (error) {once (error)} then(onpity, onRejected) { if (this.status === FULFILLED) { onFulfilled(this.value) } if (this.status === REJECTED) { OnRejected (this.reason)} if (this.status === PENDING) {// If (this.status === PENDING) Will push the callback function to store success/failure of the callback function enclosing onResolvedCallbacks. Push (() = > {onFulfilled (enclosing the value)}) this.onRejectedCallbacks.push(() => { onRejected(this.reason) }) } } } const promise = new Promise((resolve, Reject) => {setTimeout(() => {resolve(' succeed '); }, 1000); }).then( (data) => { console.log('success', data) }, (err) => { console.log('faild', err) } )Copy the code