1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
| class Promise { static PENDING = "待定"; static FULFILLED = "成功"; static REJECTED = "拒绝"; constructor(func) { this.status = Promise.PENDING; this.result = null; this.resolveCallbacks = []; this.rejectCallbacks = []; try { func(this.resolve.bind(this), this.reject.bind(this)); } catch (error) { this.reject(error); } } resolve(result) { setTimeout(() => { if (this.status === Promise.PENDING) { this.status = Promise.FULFILLED; this.result = result; this.resolveCallbacks.forEach(callback => { callback(result); }) } }) } reject(result) { setTimeout(() => { if (this.status === Promise.PENDING) { this.status = Promise.REJECTED; this.result = result; this.rejectCallbacks.forEach(callback => { callback(result); }) } }) } then(onFULFILLED, onREJECTED) { onREJECTED = typeof onREJECTED === 'function' ? onREJECTED : () => {}; onFULFILLED = typeof onFULFILLED === 'function' ? onFULFILLED : () => {}; if (this.status === Primise.PENDING) { this.resolveCallbacks.push(onFULFILLED); this.rejectCallbacks.push(onREJECTED); }; if (this.status === Promise.FULFILLED) { setTimeout(() => { onFULFILLED(this.result); }) } if (this.status === Promise.REJECTED) { setTimeout(() => { onREJECTED(this.result); }) } return this; } }
let promise = new Promise((resolve, reject) => { resolve("一切正常"); }) promise.then( result => {console.log(result)}, result => {console.log(result.message)} );
|