const PENDING = 'PENDING';
const FULFILLED = 'FULFILLED';
const REJECTED = 'REJECTED';
class myPromise {
constructor(executor) {
this.status = PENDING;
this.value = undefined;
this.reason = undefined;
this.onResolveCallbacks = [];
this.onRejectCallbacks = [];
let resolve = (value) => {
this.status = FULFILLED;
this.value = value;
this.onResolveCallbacks.forEach((fn) => fn());
}
let reject = (reason) => {
this.status = REJECTED;
this.reason = reason;
this.onRejectCallbacks.forEach((fn) => fn());
}
try {
executor(resolve, reject);
} catch (error) {
reject(error);
}
};
then(onFulfilled, onRejected) {
onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : (value) => value;
onRejected = typeof onRejected === 'function' ? onRejected : (error) => {
throw error;
};
let promise2 = new myPromise((resolve, reject) => {
if (this.status === FULFILLED) {
setTimeout(() => {
try {
let x = onFulfilled(this.value);
this.resolvePromise(promise2, x, resolve, reject);
} catch (error) {
reject(error);
}
}, 0);
};
if (this.status === REJECTED) {
setTimeout(() => {
try {
let x = onRejected(this.reason);
this.rejectedPromise(promise2, x, resolved, reject);
} catch (error) {
reject(error);
}
}, 0);
};
if (this.status === PENDING) {
this.onResolveCallbacks.push(() => {
setTimeout(() => {
try {
let x = onFulfilled(this.value);
this.resolvePromise(promise2, x, resolve, reject);
} catch (error) {
reject(error);
}
}, 0);
});
this.onRejectCallbacks.push(() => {
setTimeout(() => {
try {
let x = onRejected(this.value);
this.onRejectCallbacks(promis2, x, resolve, reject);
} catch (error) {
reject(error);
}
}, 0);
});
}
});
return promise2;
};
catch(reject) {
return this.then(null, reject);
};
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 {
let then = x.then;
if (typeof then === 'function') {
then.call(x, (y) => {
if (called) return;
called = true;
this.resolvePromise(promise2, y, resolve, reject);
}, (error) => {
if (called) return;
called = true;
reject(error);
})
} else {
resolve(x);
}
} catch (error) {
if (called) return;
called = true;
reject(error);
};
}else{
resolve(x);
}
};
};
const test1 = new myPromise((resolve,reject) => {
resolve(1);
},() => {
reject(2);
});
test1.then((vale) => {
console.log('value===',value);
});
console