Promise的实现主要有以下几个方法:
构造函数 - 创建一个Promise实例。
then() - 处理成功和失败的回调函数,并返回一个新的Promise实例。
catch() - 处理Promise的reject状态,并返回一个新的Promise实例。
resolvePromise() - 根据Promise链式调用的结果,决定是否继续执行。
class MyPromise {constructor(executor) {this.status = 'pending';this.value = undefined;this.reason = undefined;this.onFulfilledCallbacks = [];this.onRejectedCallbacks = [];const resolve = (value) => {if (this.status === 'pending') {this.status = 'fulfilled';this.value = value;this.onFulfilledCallbacks.forEach((callback) => callback(this.value));}};const reject = (reason) => {if (this.status === 'pending') {this.status = 'rejected';this.reason = reason;this.onRejectedCallbacks.forEach((callback) => callback(this.reason));}};try {executor(resolve, reject);} catch (error) {reject(error);}}then(onFulfilled, onRejected) {onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : (value) => value;onRejected = typeof onRejected === 'function' ? onRejected : (reason) => { throw reason };const promise2 = new MyPromise((resolve, reject) => {if (this.status === 'fulfilled') {setTimeout(() => {try {const x = onFulfilled(this.value);this.resolvePromise(promise2, x, resolve, reject);} catch (error) {reject(error);}}, 0);} else if (this.status === 'rejected') {setTimeout(() => {try {const x = onRejected(this.reason);this.resolvePromise(promise2, x, resolve, reject);} catch (error) {reject(error);}}, 0);} else if (this.status === 'pending') {this.onFulfilledCallbacks.push((value) => {setTimeout(() => {try {const x = onFulfilled(value);this.resolvePromise(promise2, x, resolve, reject);} catch (error) {reject(error);}}, 0);});this.onRejectedCallbacks.push((reason) => {setTimeout(() => {try {const x = onRejected(reason);this.resolvePromise(promise2, x, resolve, reject);} catch (error) {reject(error);}}, 0);});}});return promise2;}catch(onRejected) {return this.then(null, onRejected);}resolvePromise(promise2, x, resolve, reject) {if (promise2 === x) {reject(new TypeError('Chaining cycle detected'));}let called = false;if (x !== null && (typeof x === 'object' || typeof x === 'function')) {try {const then = x.then;if (typeof then === 'function') {then.call(x, (y) => {if (called) return;called = true;this.resolvePromise(promise2, y, resolve, reject);}, (r) => {if (called) return;called = true;reject(r);});} else {resolve(x);}} catch (error) {if (called) return;called = true;reject(error);}} else {resolve(x);}}
}