skip to Main Content

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


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

    Login or Signup to reply.
  2. Pay attention to what is running inside .then functions, particularly if they don’t participate in main‘s resolve/reject response. Unfinished asynchronous processes that don’t participate in your await call will continue to run until they complete. The example below will sleep for 10 seconds after logging the line "*** Finished Processing MAIN".

    const fsp = require('fs').promises;
    
    function sleep(ms) {
      return new Promise((resolve) => {
        setTimeout(resolve, ms);
      });
    }
    
    async function main() {
        try {
          fsp.readdir("/").then(async (files) => {
              // Perform a simple task
              for (const file of files)
                console.log(file);
              // Simulate a longer task.
              await sleep(10000);
          });
        } catch (err) {
          console.error(err);
        } 
        console.log('* Returning from main');
        return "done";
    }
    
    (async function() {
        await main();    
        console.log(`*** Finished Processing MAIN`);
    })();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search