Promises don't hold up the event loop

A fun thing I came across recently: a pending promise, by itself, won't stop a Node.js script from exiting.

Let's say we have a script that ends with something like this:

someFunctionThatReturnsAPromise();

Note that we aren't await-ing this promise or doing anything with its result. If we run this script, will the Node.js process wait for the promise to resolve before exiting?

Well, it depends (🙄). Promises by themselves don't hold up the event loop. This means that Node.js will not wait around for your promise to be fulfilled, unless...

Unless the promise does something that does hold up the event loop, such as network (calling an API), I/O (reading a file, querying a database) or timers (setTimeout, etc). These are asynchronous operations that add callbacks to Node.js' task queues (the queues are lists of operations which tell Node.js the next thing to do), and Node.js won't exit until the queues are empty.

So, it does depend. If the promise does some asynchronous operation, then likely, yes, Node.js will wait until it resolves (or rejects), even if that takes forever. Otherwise, it'll happily exit. You shouldn't need to worry about this, as most Promise-based operations do async stuff, but occasionally it can come in handy (for instance, if you're wrapping a sync operation with a Promise).



I write about my software engineering learnings and experiments. Stay updated with Tentacle: tntcl.app/blog.shalvah.me.

Powered By Swish