3

I have this strange problem with the code below: adding an infinite loop after a function call will prevent promises from resolving, inside the call.

I don't understand why, and how this loop can influence promise behaviour

const second_call = () => {
    return new Promise((resolve, reject) => {
        console.log("Second call");
        resolve();
    });
}

const first_call = () => {
    console.log("First call");
    second_call().then(() => {
        console.log("First call, THEN");
    });
}

const main = () => {
    console.log("Started");
    first_call();
    //if if comment the while (true), all debug msgs will be displayed
    //if i uncomment the while (true), the msg "First call, THEN" will not be displayed
    while (true);
}

main();
Bharata
  • 13,509
  • 6
  • 36
  • 50
  • 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 23 '18 at 23:22

1 Answers1

5

You are keeping the EventLoop busy with that infinite loop. Node is single threaded and uses a set of mechanisms to handle concurrent operations. In this case, your promise is waiting for the EventLoop to be available to settle the promise result but since you have a infinite thing happening, the promise is never picked up and resolved.

I suggest you to read about how EventLoop works and concurrency in NodeJS.

Here are some good references:

Fabian Rivera
  • 1,138
  • 7
  • 15
  • So, if i want to fix it, what would be a good idea? Just waiting for the first call? – LeChatErrant Aug 23 '18 at 18:29
  • If you are using Node v.8 or above, you can use async/await. Basically, the functions that return a promise need to be marked as async functions and you need to use await in front of the call to first_call(). Here are some usage examples: https://gist.github.com/faabianr/ee965520c6035d3272ee38071955ae8f#file-async-await-js – Fabian Rivera Aug 23 '18 at 18:31
  • @LeChatErrant There is nothing to fix. Just don't do an infinite loop. If you want to run code repeatedly use setTimeout or setInterval – Paul Aug 23 '18 at 18:35