class myPromise {
constructor (executor) {
this.status = 'pending';
this.result = null;
this.reason = null;
this.onFullfilledCallBacks = [];
this.onRejectedCallBacks = [];
try {
constructor(this.resolve.bind(this), this.reject.bind(this));
} catch (error) {
this.reject(error);
}
}
resolve (result) {
if (this.status = 'pending') {
this.status = 'fullfilled';
this.result = result;
this.onFullfilledCallBacks.forEach(callback => {
callback(result);
});
}
}
reject (reason) {
if (this.status = 'pending') {
this.status = 'rejected';
this.reason = reason;
this.onRejectedCallBacks.forEach(callback => {
callback(reason);
});
}
}
then (onFullfilled, onRejected) {
let promise2 = new Promise((resolve, reject) => {
if (this.status = 'fullfilled') {
setTimeout(() => {
try {
if (typeof onFullfilled !== 'function') {
resolve(reason);
} else {
let x = onFullfilled(this.result);
resolvePromise(promise2, x, resolve, reject);
}
} catch (error) {
reject(error);
}
});
} else if (this.status = 'rejected') {
setTimeout(() => {
try {
if (typeof onRejected !== 'function') {
resolve(reason);
} else {
let x = onRejected(this.reason);
resolvePromise(promise2, x, resolve, reject);
}
} catch (error) {
reject(error);
}
});
} else if (this.status = 'pending') {
this.onFullfilledCallBacks.push(() => {
setTimeout(() => {
try {
if (typeof onFullfilled !== 'function') {
resolve(reason);
} else {
let x = onFullfilled(this.result);
resolvePromise(promise2, x, resolve, reject);
}
} catch (error) {
reject(error);
}
});
});
this.onRejectedCallBacks.push(() => {
setTimeout(() => {
try {
if (typeof onRejected !== 'function') {
resolve(reason);
} else {
let x = onRejected(this.reason);
resolvePromise(promise2, x, resolve, reject);
}
} catch (error) {
reject(error);
}
});
});
}
});
return promise2;
}
}
function resolvePromise (promise2, x, resolve, reject) {
if (x === promise2) {
throw new TypeError('Promise error');
}
if (x instanceof myPromise) {
x.then(y => {
resolvePromise(promise2, y, resolve, reject);
}, reject)
} else if (x !== null && ((typeof x === 'object' || (typeof x === 'function')))) {
let called = true;
try {
let then = x.then;
} catch (error) {
return reject(error);
}
if (typeof then === 'function') {
try {
then.call(
x,
y => {
if (called) return;
called = true;
resolvePromise(promise2, y, resolve, reject);
},
r => {
if (called) return;
called = true;
reject(r);
}
)
} catch (error) {
if (called) return;
called = true;
reject(error);
}
} else {
resolve(x);
}
} else {
return resolve(x);
}
}
手写Promise
最新推荐文章于 2024-10-12 10:41:56 发布
该文章描述了一个自定义的Promise类实现,包括构造函数接收executor参数来执行resolve和reject,管理pending、fulfilled和rejected三种状态,以及then方法处理成功和失败的回调函数,支持链式调用。同时,文章涉及到对thenable对象的处理和错误捕获机制。
摘要由CSDN通过智能技术生成