总结一下 Promise,怎么使用,如何手写 promise
function MyPromise(executor) {
this.status = 'pending'; // 初始状态
this.value = undefined; // 存放异步操作的结果
this.reason = undefined; // 存放错误原因
this.onFulfilledCallbacks = []; // 存放成功的回调函数
this.onRejectedCallbacks = []; // 存放失败的回调函数
// 更改 Promise 的状态
function resolve(value) {
if (this.status === 'pending') {
this.status = 'fulfilled';
this.value = value;
this.onFulfilledCallbacks.forEach(fn => fn());
}
}
function reject(reason) {
if (this.status === 'pending') {
this.status = 'rejected';
this.reason = reason;
this.onRejectedCallbacks.forEach(fn => fn());
}
}
// 捕获 executor 执行器中的错误
try {
executor(resolve.bind(this), reject.bind(this));
} catch (e) {
reject.call(this, e);
}
// 实现 then 方法
MyPromise.prototype.then = function(onFulfilled, onRejected) {
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : value => value;
onRejected = typeof onRejected === 'function' ? onRejected : reason => { throw reason; };
return new MyPromise((resolve, reject) => {
if (this.status === 'fulfilled') {
setTimeout(() => {
try {
let x = onFulfilled(this.value);
resolvePromise(resolve, reject, x);
} catch (e) {
reject(e);
}
});
} else if (this.status === 'rejected') {
setTimeout(() => {
try {
let x = onRejected(this.reason);
resolvePromise(resolve, reject, x);
} catch (e) {
reject(e);
}
});
} else {
this.onFulfilledCallbacks.push(() => {
setTimeout(() => {
try {
let x = onFulfilled(this.value);
resolvePromise(resolve, reject, x);
} catch (e) {
reject(e);
}
});
});
this.onRejectedCallbacks.push(() => {
setTimeout(() => {
try {
let x = onRejected(this.reason);
resolvePromise(resolve, reject, x);
} catch (e) {
reject(e);
}
});
});
}
});
};
// 辅助函数,处理 then 或 catch 中的返回值
function resolvePromise(resolve, reject, x) {
// ... 省略了一些复杂的处理逻辑,如处理 x 为 Promise 的情况
if (x !== promise2) { // 避免自引用
if (x instanceof MyPromise) {
x.then(resolve, reject);
} else {
resolve(x);
}
}
}
}