🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
## 手写 promise ``` class Promise { constructor(executor) { this.init() try { executor(this.resolve, this.reject) } catch (err) { this.reject(err) } } init () { this.value = '' this.reason = '' this.onFulFilledCallbacks = [] this.onRejectedCallbacks = [] this.state = Promise.PENGING } resolve = value => { // 1. 改变promise状态 // 2. 返回结果 if (this.state === Promise.PENGING) { this.state = Promise.FULFILLED this.value = value this.onFulFilledCallbacks.forEach(item => item(this.value)) } } reject = reason => { // 1. 改变promise状态 // 2. 返回拒绝的原因 if (this.state === Promise.REJECTED) { this.state = Promise.FULFILLED this.reason = reason this.onRejectedCallbacks.forEach(item => item(this.reason)) } } then = (onFulFilled, onRejected) => { if (typeof onFulFilled !== 'function') { onFulFilled = function (value) { return value } } if (typeof onRejected !== 'function') { onRejected = function (reason) { throw reason } } if (this.state === Promise.FULFILLED) { setTimeout(() => { onFulFilled(this.value) }); } if (this.state === Promise.REJECTED) { setTimeout(() => { onRejected(this.reason) }); } if (this.state === Promise.PENGING) { this.onFulFilledCallbacks.push(() => { setTimeout(() => { onFulFilled(this.value) }) }) this.onRejectedCallbacks.push(() => { setTimeout(() => { onRejected(this.reason) }) }) } } } Promise.PENGING = 'pending' Promise.FULFILLED = 'fulfilled' Promise.REJECTED = 'rejected' console.log('1') new Promise((resolve, reject) => { setTimeout(() => { console.log('start') resolve(1) }) }) .then(res => { console.log('2') // console.log(res, ':res') }, reason => { // console.log(reason, ':reason') }) console.log('3') ```