I have inherited some node js code, which gets called using command line parameters such as node. –op (where the whatever can be doProcessA, doProcessB, etc.)
Each of these processes does different things, such as reading data from an API, writing data to an SDQL Server table, etc
The code is all called via this very last part of index.js
(async function() {
await main();
console.log(`*** Finished Processing MAIN`);
})();
The main()
function handles all of the code to do the processing and uses various async functions
to do whatever is required.
There are various console.log
statements that put out sensible things in a sensible order. Bottom line – it all works fine.
When running this (for example, ‘node . –op doProcessA’ from the command prompt, it works fine, it puts out the various console.log messages for process A, and then it puts out the final *** Finished Processing MAIN
message, and then there is a delay of (approx) 20 seconds before it then drops back to the command line. I’m wondering why this is , because from what I can see, all the actual processing is finished.
2
Answers
Node.js uses an event-driven, non-blocking I/O model. It has an event loop that continuously checks for any pending tasks or events. It is possible that after the main processing is completed, the event loop is still running and waiting for any remaining tasks(Background process of node –op) to be processed before exiting.
Pay attention to what is running inside
.then
functions, particularly if they don’t participate inmain
‘s resolve/reject response. Unfinished asynchronous processes that don’t participate in yourawait
call will continue to run until they complete. The example below will sleep for 10 seconds after logging the line "*** Finished Processing MAIN".