class SimplePromise {
constructor(executor) {
this.state = 'pending';
this.value = undefined;
this.callbacks = [];
const resolve = (value) => {
if (this.state !== 'pending') return;
this.state = 'fulfilled';
this.value = value;
this.flush();
}
const reject = (error) => {
if (this.state !== "pending") return;
this.state = 'rejected';
this.value = error;
this.flush();
}
try {
executor(resolve, reject);
} catch (e) {
reject(e);
}
}
flush() {
while(this.callbacks.length) {
const {onFulfilled, onReject} = this.callbacks.shift();
this.handle(onFulfilled, onReject);
}
}
handle(onFulfilled, onReject) {
queueMicrotask(() => {
console.log(this.state);
if(this.state === 'fulfilled' && onFulfilled) {
onFulfilled(this.value);
} else if(this.state === 'rejected') {
console.log(this.state);
onReject(this.value);
}
})//queueMicrotask
}
then(onFulfilled, onReject) {
return new SimplePromise((resolve, reject) => {
const fullfieldHandler = (value) => {
try {
const result = onFulfilled ? onFulfilled(value) : value;
resolve(result);
} catch(e) {
reject(e);
}
}
const rejectHandler = (error) => {
console.log(error);
try {
if (onReject) {
resolve(onReject(error));
} else {
reject(error);
}
} catch (e) {
reject(e);
}
}
if (this.state === 'pending') {
this.callbacks.push({onFulfilled: fullfieldHandler, onReject: rejectHandler})
} else {
this.handle(fullfieldHandler, rejectHandler);
}
})
}
catch(onRejected) {
return this.then(null, onRejected);
}
}
new SimplePromise(function (resolve, reject) {
reject(new Error('failed'));
}).catch(function (error) {
console.log(error.message); // 'failed'
});
Code will run automatically after changes.
Code runs in an isolated environment.
Code runs in an isolated environment.