UNPKG

wft-utils

Version:

The commonly used tool functions in daily development

63 lines 1.76 kB
// 简单手写一个Promise class MyPromise { static PENDING = 'pending' static FULFILLED = 'fulfilled' static REJECTED = 'rejected' constructor(fn) { this.status = MyPromise.PENDING this.result = null this.resolveCallbacks = [] this.rejectCallbacks = [] try { fn(this.resolve.bind(this), this.reject.bind(this)) } catch (e) { this.reject(e) } } resolve(data) { setTimeout(() => { if (this.status === MyPromise.PENDING) { this.status = MyPromise.FULFILLED this.result = data if (this.resolveCallbacks.length) { this.resolveCallbacks.forEach(callback => { callback(data) }) } } }) } reject(err) { setTimeout(() => { if (this.status === MyPromise.PENDING) { this.status = MyPromise.REJECTED this.result = err if (this.rejectCallbacks.length) { this.rejectCallbacks.forEach(callback => { callback(err) }) } } }) } then(ONFULFILLED, ONREJECTED) { return new MyPromise((resolve, reject) => { ONFULFILLED = typeof ONFULFILLED === 'function' ? ONFULFILLED : () => { } ONREJECTED = typeof ONREJECTED === 'function' ? ONREJECTED : () => { } if (this.status === MyPromise.PENDING) { this.resolveCallbacks.push(ONFULFILLED) this.rejectCallbacks.push(ONREJECTED) } if (this.status === MyPromise.FULFILLED) { setTimeout(() => { ONFULFILLED(this.result) }) } if (this.status === MyPromise.REJECTED) { setTimeout(() => { ONREJECTED(this.result) }) } }) } }