class MyPromise{
constructor(callback){
this.status = 'pending';
this.value = undefined;
this.reason = undefined;
this.onResolvedCallbacks = [];
this.onRejectedCallbacks = [];
const resolve = value => {
if(this.status === 'pending'){
this.status = 'resolved';
this.value = value;
this.onResolvedCallbacks.forEach(cb => cb());
}
}
const reject = reason => {
if(this.status === 'pending'){
this.status = 'rejected';
this.reason = this.reason;
this.onRejectedCallbacks.forEach(cb => cb());
}
}
callback(resolve, reject);
}
then(onResolved, onRejected){
const newPromise = new MyPromise((resolve, reject) => {
if(this.status === 'resolved') {
try {
const x = onResolved(this.value);
resolve(x)
} catch (error) {
reject(error)
}
}
if(this.status === 'rejected') {
try {
const x = onRejected(this.reason);
resolve(x)
} catch (error) {
reject(error)
}
}
if(this.status === 'pending') {
this.onResolvedCallbacks.push(()=>{
try {
const x = onResolved(this.value);
resolve(x)
} catch (error) {
reject(error)
}
})
this.onRejectedCallbacks.push(()=>{
try {
const x = onRejected(this.reason);
resolve(x)
} catch (error) {
reject(err)
}
})
}
})
return newPromise
}
catch(onRejected){
return this.then(null, onRejected);
}
};