class CcPromise {
constructor(fn) {
this.state = 'pending';
this.value = '';
this.resolveCallbacks = [];
this.rejectCallbacks = [];
this.resolve = (value) => {
if (this.state === 'pending') {
this.state = 'fulfilled';
this.value = value;
this.resolveCallbacks.forEach(fn => fn());
}
};
this.reject = (value) => {
if (this.state === 'pending') {
this.state = 'rejected';
this.value = value;
this.rejectCallbacks.forEach(fn => fn());
}
};
try {
fn(this.resolve, this.reject);
} catch (e) {
this.reject(e);
}
}
then(resolve, reject) {
if (this.state === 'fulfilled') {
resolve(this.value);
}
if (this.state === 'rejected') {
reject(this.value);
}
if (this.state === 'pending') {
this.resolveCallbacks.push(() => {
resolve(this.value);
});
this.rejectCallbacks.push(() => {
resolve(this.value);
});
}
}
}
const p = () => new CcPromise((resolve, reject) => {
setTimeout(() => {
resolve('You so good, just go ahead!')
}, 1000)
});
p().then(res => { console.log(res) });