class Promise {
constructor(executor) {
// 初始化 Promise 状态和值
this.state = 'pending';
this.value = undefined;
this.reason = undefined;
// 初始化 Promise 的回调函数数组
this.onResolvedCallbacks = [];
this.onRejectedCallbacks = [];
// 定义 resolve 和 reject 函数
const resolve = value => {
if (this.state === 'pending') {
// 修改 Promise 的状态和值
this.state = 'fulfilled';
this.value = value;
// 执行 Promise 的 onResolvedCallbacks 数组中的回调函数
this.onResolvedCallbacks.forEach(cb => cb());
}
};
const reject = reason => {
if (this.state === 'pending') {
// 修改 Promise 的状态和值
this.state = 'rejected';
this.reason = reason;
// 执行 Promise 的 onRejectedCallbacks 数组中的回调函数
this.onRejectedCallbacks.forEach(cb => cb());
}
};
// 执行 executor 函数,并在执行过程中调用 resolve 和 reject 函数
try {
executor(resolve, reject);
} catch (err) {
reject(err);
}
}
then(onFulfilled, onRejected) {
// 如果 onFulfilled 和 onRejected 不是函数,则忽略它们
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value;
onRejected = typeof onRejected === 'function' ? onRejected : reason => { throw reason };
// 创建一个新的 Promise 对象
const promise2 = new Promise((resolve, reject) => {
// 当前 Promise 的状态为 fulfilled 时,异步执行 onFulfilled 函数
if (this.state === 'fulfilled') {
setTimeout(() => {
try {
// 获取 onFulfilled 函数的返回值 x,并将其传递给 resolvePromise 处理
const x = onFulfilled(this.value);
resolvePromise(promise2, x, resolve, reject);
} catch (err) {
reject(err);
}
});
}
// 当前 Promise 的状态为 rejected 时,异步执行 onRejected 函数
else if (this.state === 'rejected') {
setTimeout(() => {
try {
// 获取 onRejected 函数的返回值 x,并将其传递给 resolvePromise 处理
const x = onRejected(this.reason);
resolvePromise(promise2, x, resolve, reject);
} catch (err) {
reject(err);
}
});
}
// 当前 Promise 的状态为 pending 时,将 onFulfilled 和 onRejected 函数分别添加到数组中
else {
this.onResolvedCallbacks.push(() => {
setTimeout(() => {
try {
// 获取 onFulfilled 函数的返回值 x,并将其传递给 resolvePromise 处理
const x = onFulfilled(this.value);
resolvePromise(promise2, x, resolve, reject);
} catch (err) {
reject(err);
}
});
});
this.onRejectedCallbacks.push(() => {
setTimeout(() => {
try {
// 获取 onRejected 函数的返回值 x,并将其传递给 resolvePromise 处理
const x = onRejected(this.reason);
resolvePromise(promise2, x, resolve, reject);
} catch (err) {
reject(err);
}
});
});
}
});
return promise2;
}
catch(onRejected) {
return this.then(null, onRejected);
}
}
function resolvePromise(promise2, x, resolve, reject) {
if (promise2 === x) {
return reject(new TypeError('Chaining cycle detected for promise'));
}
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;
resolvePromise(promise2, y, resolve, reject);
},
r => {
if (called) return;
called = true;
reject(r);
}
);
} else {
resolve(x);
}
} catch (err) {
if (called) return;
called = true;
reject(err);
}
} else {
resolve(x);
}
}
手写Promise
于 2023-03-31 11:14:38 首次发布