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