直接上代码
class MYPromise { static PADDING = 'padding' static FULFILLED = 'fulfilled' static REJECTED = 'rejected' constructor(execute) { this.state = MYPromise.PADDING;// 初始化 状态 this.value = undefined;// 初始化 成功值 this.reason = undefined;// 初始化 失败值 this.onResolvedCallback = [];// 成功回调存起来的数组 this.onRejectedCallback = [];// 失败 let resolve = value => { if (this.state == MYPromise.PADDING) { this.value = value;// 赋值 this.state = MYPromise.FULFILLED;// 改变状态 this.onResolvedCallback.forEach(fn => fn(value)); } } let reject = reason => { if (this.state = MYPromise.PADDING) { this.reason = reason;// 赋值 this.state = MYPromise.REJECTED;// 改变状态 this.onRejectedCallback.forEach(fn => fn(reason)) } } try { // 默认状态是 padding 等待,resolve 执行改变状态为成功,reject 执行,改变状态为失败 execute(resolve, reject) } catch (err) { reject(err) } } // then 有两个参数,第一个是成功回调,第二个是失败回调 // 两个参数都是函数 static then(onFulfilled, onRejected) { if (this.state = MYPromise.FULFILLED) { onFulfilled(this.value); } if (this.state = MYPromise.REJECTED) { onRejected(this.reason) } if (this.state == MYPromise.PADDING) { this.onResolvedCallback.push(onFulfilled); this.onRejectedCallback.push(onRejected); } } static all(promises) { let resolveArr = [] return new MYPromise((resolve, reject) => { promises.forEach(promise => { promise.then(value => { resolveArr.push(value); if (resolveArr.length == promises.length) { resolve(resolveArr); } }, reason => { reject(reason) }) }) }) } static race(promises) { return new MYPromise((resolve, reject) => { promises.forEach(promise => { promise.then(value => { resolve(value) }, reason => { reject(reason) }) }) }) } } let p = new MYPromise((resolve, reject) => { resolve('成功'); // reject('失败') }) let p2 = new MYPromise((resolve, reject) => { resolve('成功'); // reject('失败') }) p.then(resolve => { }, reject => { }) MYPromise.all([p, p2]).then(resolve => { console.log('成功'); }, reject => { } ) MYPromise.race([p, p2]).then(resolve => { }, reject => { } )