版本一,构造函数
1function MyPromise(fn = () => {}) { 2 // const this = {} 3 this.state = 'pending' 4 this.value = undefined 5 6 const resolve = (value) => { 7 if (this.state === 'pending') { 8 this.state = 'fulfilled' 9 this.value = value 10 } 11 } 12 const reject = (value) => { 13 if (this.state === 'pending') { 14 this.state = 'rejected' 15 this.value = value 16 } 17 } 18 19 this.then = (onFulfilled, onRejected) => { 20 switch (this.state) { 21 case 'fulfilled': 22 onFulfilled(this.value) 23 break 24 case 'rejected': 25 onRejected(this.value) 26 break 27 default: 28 onRejected(this.value); 29 } 30 } 31 32 try { 33 fn(resolve, reject) 34 } catch (e) { 35 reject(e) 36 } 37}
版本二,class类
1class MyPromise { 2 constructor (fn) { 3 this.state = 'pending' 4 this.value = undefined 5 let resolve = value => { 6 if (this.state === 'pending') { 7 this.state = 'fulfilled' 8 this.value = value 9 } 10 } 11 let reject = value => { 12 if (this.state === 'pending') { 13 this.state = 'rejected' 14 this.value = value 15 } 16 } 17 // 自动执行函数 18 try { 19 fn(resolve, reject) 20 } catch (e) { 21 reject(e) 22 } 23 } 24 // then 25 then(onFulfilled, onRejected) { 26 switch (this.state) { 27 case 'fulfilled': 28 onFulfilled(this.value) 29 break 30 case 'rejected': 31 onRejected(this.value) 32 break 33 default: 34 onRejected(this.value); 35 } 36 } 37}
实例化执行
1new MyPromise((resolve, reject) => { 2 console.log('in Promise...') 3 resolve(111) 4}).then((val) => { 5 console.log('resolve', val) 6}, (e) => { 7 console.log('rejected', e) 8})
