class Promise { constructor(fn) { this.status = 'pending'; this.onFulfilledCallbacks = []; this.onRejectedCallbacks = []; // 更改成功后的状态 const resolve = value => { if (this.status === 'pending') { this.status = 'fulfilled'; this.onFulfilledCallbacks.forEach(fn => fn(value)); } } // 更改失败后的状态 const reject = err => { if (this.status === 'pending') { this.status = 'rejected'; this.onRejectedCallbacks.forEach(fn => fn(err)); } } try { fn(resolve, reject) } catch(err) { reject(err) } } then(onFulfilled, onRejected) { onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : v => v; onRejected = typeof onRejected === 'function' ? onRejected : err => {throw err}; // 为了链式调用,这里直接返回一个 Promise return new Promise((resolve, reject) => { const fulfilledMicrotask = value => { queueMicrotask(() => { try { const res = onFulfilled(value); res instanceof Promise ? res.then(resolve, reject) : resolve(res); } catch(err) { reject(err); } }) } const rejectedMicrotask = value => { queueMicrotask(() => { try { const res = onRejected(value); res instanceof Promise ? res.then(resolve, reject) : reject(res); } catch(err) { reject(err); } }) } this.onFulfilledCallbacks.push(fulfilledMicrotask); this.onRejectedCallbacks.push(rejectedMicrotask); }); } static resolve(value) { if (value instanceof Promise) { return value; } return new Promise(resolve => { resolve(value); }); } static reject(err) { return new Promise((resolve, reject) => { reject(err); }); } }