Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How come awaiting an empty JavaScript Promise does not keep the runtime alive?

I was expecting the following snippet to hang forever since the promise is never neither fulfilled nor rejected, instead the JavaScript runtime is simply terminated and the code after the await is never executed.

(async function () {
    console.log('so far so good');
    await new Promise(() => {});
    console.log('never printed');
})();

What's worse is that the above also happens dynamically, that is when the Promise becomes impossible to fulfill/reject after a certain event, for example the following only keep the runtime alive for one second:

(async function () {
    console.log('so far so good');
    await new Promise((fulfill, reject) => {
        const timeout = setTimeout(fulfill, 2000);
        setTimeout(() => {
            clearTimeout(timeout);
        }, 1000);
    });
    console.log('never printed');
})();

This is counterintuitive to say the least, what's the rationale behind this? More importantly can you link me to a document/spec that deals with this behavior?

like image 519
cYrus Avatar asked Jun 15 '26 22:06

cYrus


2 Answers

An unfulfilled promise does not keep node.js alive by itself. It takes an underlying uncompleted async operation that is still alive (usually with some native code behind it) for node.js to automatically stay alive.

Examples of things that automatically keep node.js alive are open sockets, timers that haven't fired, etc...

An unfulfilled promise is just a Javascript object sitting in memory. It has no more effect on the lifetime of a node.js process than any other object in node.js. Keep in mind that a promise is JUST a notification scheme where you can register an interest in a resolve or reject event for a particular operation (kind of like an event emitter with special features). It's the underlying async operation (which is usually backed by native code that runs the async operation) which actually holds the process open. The promise itself doesn't affect the process itself at all.

like image 118
jfriend00 Avatar answered Jun 17 '26 12:06

jfriend00


As far as I could understand your confusion here, the explanation is :

When you write an async function, it returns a promise which is not resolved as expression of await is never resolved and that promise is pending. Worth a readh : mdn doc for async

Now it won't block the main thread execution. What happens to the unresolved promises can be read here in one of the SO's answer : unresolved promises

like image 44
binariedMe Avatar answered Jun 17 '26 11:06

binariedMe