I'm working on the following JS practice. Somehow promise.then
is not getting triggered. I use VS Code with Node. I wonder why or what I did wrong. See my code below. Thanks!
Update: After some testing, I realized the first callback was not resolving b/c I had an infinite while
loop. It worked when the while loop was not there.
A hypothesis I have is that because JS is single threaded, the while
loop takes away all the resources, and thus the async function never gets a chance to resolve... does this sound right?
function mySetInterval(callback, interval) {
let prevTime = new Date().getTime();
let finish = false;
callback().then((msg) => {
console.log('This callback is never triggered ', msg);
finish = true;
})
.catch((msg)=> {
console.log('This callback is never triggered either ', msg);
});
while (true) {
let newTime = new Date().getTime();
if ((prevTime + interval) <= newTime){
if (finish) {
finish = false;
callback()
.then((successMsg) => {
finish = true;
console.log('Of course this callback is never triggered, cuz the first one is never triggered ', successMsg);
});
}
prevTime = newTime;
}
}
}
mySetInterval(() => {
return new Promise((resolve, reject) => {
resolve(new Date().getTime());
});
}, 500);