0

I want to finish a promise task outside the task itself, just like some language can kill process/thread. Seeing from this question, I implemented my code as below. However, the promise still continues after counting to 5. I would be grateful if somebody can help me with this.

let resolveCurrentPromise = () => {};

const longTimeHandler = async () => {
  let counter = 0;
  while (true) {
    console.log(counter++);
    await new Promise((res) => {
      setTimeout(res, 1000);
    });
    if (counter === 5) {
      resolveCurrentPromise();
    }
  }
};

(async () => {
  await new Promise((res) => {
    resolveCurrentPromise = res;
    longTimeHandler();
  });
})();
Ji Frank
  • 71
  • 1
  • 6
  • 1
    You never break out of the `while` loop. – Barmar Jun 26 '23 at 21:34
  • Add `break` after the call to `resolveCurrentPromise()`. – Barmar Jun 26 '23 at 21:40
  • Why are you even `await`ing the `new Promise` if you do nothing afterwards? – Bergi Jun 26 '23 at 21:54
  • *"However, the promise still continues after counting to 5."*: no, the promise resolved. It is your `while` loop that keeps going on. It is quite easy to see with debugging that your promise resolved... – trincot Jun 27 '23 at 12:44

0 Answers0