admin管理员组

文章数量:1277361

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 e 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.

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 e 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.

Share Improve this question edited Mar 27, 2023 at 15:41 T.J. Crowder 1.1m199 gold badges2k silver badges1.9k bronze badges asked Mar 27, 2023 at 15:23 WajahathWajahath 4,0583 gold badges34 silver badges48 bronze badges 8
  • 2 You didn't await myPromise. – Unmitigated Commented Mar 27, 2023 at 15:27
  • 2 Do you want your machine to hang itself until a promise that you forgot to resolve bee resolved? – InSync Commented Mar 27, 2023 at 15:27
  • 2 Are you interested in how they can know this? If no task is pending anywhere, and no event is being listened to, your Promise won't ever be resolved. – Kaiido Commented Mar 27, 2023 at 15:31
  • 2 Basically, like @Kaiido says: Node exists when there are no pending tasks. resolve => {} in your example is a function that doesn't start any new tasks. If there were a setTimeout or fetch, there would be a pending task. If you were to call resolve() there would be one, too. But since there are no tasks to run, it's' free to exit. – RickN Commented Mar 27, 2023 at 15:33
  • 1 Minor side note: It's entirely possible for a promise to be resolved without being settled (fulfilled or rejected), or indeed without it ever being settled. More in my post on promise terminology here. – T.J. Crowder Commented Mar 27, 2023 at 15:42
 |  Show 3 more ments

4 Answers 4

Reset to default 9

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.

Internally, NodeJS does use some referencing counting, eg. if you use a setTimeout, or setInterval, internally there will be some referencing counting. You can even control this to some extent, in nodeJS you can even call unref() on a the return value of setTimeout / setInterval to stop them from preventing node closing.

If you wanted to keep node open, no matter what the trick is then to have something were the reference count is greater than 0. One idea is using a MessageChannel from worker_threads.

eg.

const { MessageChannel } = require('worker_threads');
const port = new MessageChannel();
port.port1.ref();

//nodeJs will now stay open..
//and when your ready to close Node,  `port.port1.unref()

Promises are non-blocking. This means that when you invoke the asynchronous function, JavaScript does not wait for the promise to resolve. This is the whole purpose of promises: you can allow tasks to execute "in the background" (kind of) while JavaScript executes the rest of the script/function.

The side effect: If the browser/node runtime reaches the end of the script, the program will terminate, regardless of whether the Promise is resolved or not.

If you want to block JavaScript from terminating, you will have to block the main thread. Here is a solution I just came up with (if anybody has a better solution, leave it in the ments):

async function nonBlocking() { ... }

const interval = 100; // Blocks the main thread in 100 millisecond interval
const blockingInterval = setInterval(() => undefined, 100)

nonBlocking().then(value => {
    clearInterval(blockingInterval)
    // ... Rest of code here
}).catch(err => {
    clearInterval(blockingInterval)
    // ... Handle error here
})

Another slant on this is that if the promise executor function, inlined as

resolve => {
  // nothing doing with the resolve
}

doesn't record the value of resolve for later use, or create callbacks in the executor function that call the executor's resolve argument, then the executor function can't reach resolve in any of its content.

However, resolve and reject functions hold the promise they were issued for in memory since they themselves have internal access to the promise. If resolve and/or reject are not reachable in code, neither has been called, any externally stored reference(s) to the promise are not reachable either, and the promise has not been used to resolve another promise, the promise bees eligible for memory garbage collection.

The posted code contains no code referencing resolve, and the external reference to the promise, myPromise, bees unreachable after the second statement using it has been executed.

When myPromise is gargage collected, its references to resolve and reject functions of the next promise in the chain (the one returned from then) are released and so the next promise can be garbage collected, which in turn will release resolve/reject refererences to the one returned from catch.

At this point all program data has or can be garbage collected, and in short the program has run to pletion.

本文标签: javascriptWhy Nodejs does not wait for promise to resolve before exitingStack Overflow