Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why Node.js does not wait for promise to resolve before exiting?

When I execute the following code, I thought Node.js will wait till we call the resolve. Till then the myPromise will be in the <pending> state. Then how come node exits before it resolves?

The following code exits immediately!

const myPromise = new Promise(resolve => {
  // nothing doing with the resolve
});

myPromise
  .then(() => console.log('result'))
  .catch(error => console.log('error', error));

Update 1: I renamed JavaScript to Node.js to avoid confusion.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The following code exits immediately!

What keeps a Node.js process running is active in-progress work or the potential for it (pending timers, open sockets that may receive messages, etc.). So for instance, if your code had used readFile from fs/promises and the promise you were using came from that, Node.js wouldn’t just terminate at the end of the code you’ve shown, because there’s an operation in progress (reading the file). From the The Node.js Event Loop, Timers, and process.nextTick() guide:

Between each run of the event loop, Node.js checks if it is waiting for any asynchronous I/O or timers and shuts down cleanly if there are not any.

But in your example, there’s nothing in progress, Node.js isn’t waiting for anything, so it exits.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading