I’m trying to implement Promise polyfill. I am trying to implement Promise.race but it’s not working as expected. Output here should be reject to console but I’m getting nothing. Why is it not working?
I have debugged over console and for reason it never reaches the catch for MyPromise.race().
class MyPromise{
q;
resolutionState; // normal, error
currVal;
status; // resolved,rejected,pending
constructor(callback){
this.q = []
this.currVal = null
this.status = 'pending'
this.resolutionState = 'normal'
this.currKind = null
setTimeout(()=>{
callback(this.resolve.bind(this),this.reject.bind(this))
})
}
then(callback){
this.q.push({type:'then',callback})
return this
}
catch(callback){
this.q.push({type:'catch',callback})
return this
}
executeCallbacks(){
let i = 0;
while(i<this.q.length){
// console.log('this',this)
if(this.resolutionState == 'normal'){
if(this.q[i]['type'] === 'then'){
try {
this.currVal = this.q[i]['callback'](this.currVal)
i++
} catch (error) {
this.resolutionState = 'error'
this.currVal = error
i++;
}
}
else{
i++;
}
}
else{
if(this.q[i]['type'] === 'catch'){
this.currVal = this.q[i]['callback'](this.currVal)
if(this.currVal)
this.resolutionState = 'normal'
i++
}
else{
i++;
}
}
}
this.q = []
}
resolve(arg){
if(arg!=undefined)
this.currVal = arg
this.resolutionState = 'normal'
this.status = 'resolved'
this.executeCallbacks()
return this
}
reject(arg){
if(arg!=undefined)
this.currVal = arg
this.resolutionState = 'error'
this.status = 'rejected'
this.executeCallbacks()
return this
}
static async race(promises){
return new MyPromise((res,rej)=>{
promises.forEach(promise => {
try {
if(promise instanceof MyPromise || promise instanceof Promise){
promise.then(res).catch(rej)
}
else{
res(promise)
}
} catch (error) {
rej(error)
}
})
})
}
}
const promise1 = new Promise((resolve, reject) => {
setTimeout(resolve, 500, 'one');
});
const promise2 = new Promise((resolve, reject) => {
setTimeout(resolve, 100, 'two');
});
const promise3 = new Promise((resolve,reject)=>{
reject('reject')
})
MyPromise.race([promise1, promise2, promise3]).then((value) => {
console.log(value);
})
.catch(err => console.log(err));
4