0

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);
sophia.onion
  • 314
  • 3
  • 5
  • How did you go from [your original question](https://stackoverflow.com/revisions/51995818/1) to this? – Marty Aug 24 '18 at 00:12
  • This is the actual code that doesn't work. I just tested with the original simplified question and it worked, so I updated the question. – sophia.onion Aug 24 '18 at 00:14
  • `while (true)` - never do this. Unless you're in `async` function. And possibly don't do this there, too. – Estus Flask Aug 24 '18 at 00:27
  • Yeah, here the `while (true)` is an experiment. I wonder why does it break the `promise.resolve`? – sophia.onion Aug 24 '18 at 00:29
  • 2
    your hypothesis sounds correct – Jaromanda X Aug 24 '18 at 00:47
  • 1
    Other relevant answers that cover the same material in addition to the one yours was marked a duplicate of: [What is wrong with this while loop?](https://stackoverflow.com/questions/38676709/javascript-what-is-wrong-with-this-while-loop-never-ending-loop/38676722#38676722), [Can I put a loop in this server](https://stackoverflow.com/questions/41083609/how-can-i-put-a-loop-in-this-server/41083814#41083814), [Is it possible to freeze while waiting for a socket](https://stackoverflow.com/questions/50686131/is-it-possible-to-freeze-while-waiting-for-a-socket/50711823#50711823). – jfriend00 Aug 24 '18 at 03:21

0 Answers0