'Why does setTimeOut not work with my recreated promise function?
I tried recreating the Promise class of javascript with the class keyword and function closure, it works with promise functions that returns instantly, but does not work with setTimeOut. I tried adding console.log into the setTimeOut function to check, it does not even print when the time is up. Is it because of the while loop that checks for change of state in myPromise class?
// custom promise function
class MyPromise {
constructor(func) {
this.func = func;
}
resolveWrapper() {
var state = 'pending';
var value = '';
function myResolve(val) {
value = val;
state = 'resolved';
}
function myReject(val) {
value = val;
state = 'rejected';
}
function getStateValue() {
let stateValue = {
state: state,
value: value,
}
return stateValue;
}
let returnVal = {
resolve: myResolve,
reject: myReject,
getter: getStateValue,
}
return returnVal;
}
then(nextFunc) {
let stateValue = this.resolveWrapper();
let getter = stateValue.getter;
this.func(stateValue.resolve, stateValue.reject);
while (getter().state === 'pending') {
// keep checking
}
return nextFunc(getter.value);
}
}
// test
let newProm = new MyPromise((resolve, reject) => {
setTimeout(() => {
console.log('timeout');
resolve('1');
}, 1000);
})
let tst = newProm.then((val) => (console.log(val)));
console.log(tst);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
