0

I have a Node.js script that I have an array of objects which I do some processing on inside a forEach loop, I want to have it so that when the forEach loop finishes that it then runs process.exit(0)

I'm not sure how to do this and googling these things together doesn't seem to yield much for helpful results.

I want something like

let array = [] // some data here

array.forEach((item) => {
    console.log(item) // place holder
}

process.exit(0)

Now if I do this how it is the process will exit prematurely because of Node being async. I am trying to make it behave synchronously and was not sure how I could do that. I thought about a set timeout but that will not scale with what I need it to. I will never know how long it will take because the array will almost never be the same size.

How do I get it to exit the process when the forEach is complete?

joshk132
  • 1,011
  • 12
  • 37
  • Maybe give a callback function to whatever async thing you're doing inside the loop and calling `process.exit(0);` after the callback has been called array.length times? (just a thought, still feels a bit messy) – IrkenInvader Aug 15 '19 at 23:25
  • Possibly a duplicate of https://stackoverflow.com/questions/43870227/exit-from-a-nodejs-script-when-all-asynchronous-tasks-are-done – Aamir Aug 15 '19 at 23:39
  • @Aamir Sorry not a duplicate as that is promise.all and dealing with promises not foreach loops, they work differently. – joshk132 Aug 15 '19 at 23:47
  • @JoshKirby your only choice really is to use Promises. (Note that `async` and `await` are really Promises under the hood.) – Pointy Aug 15 '19 at 23:56

1 Answers1

-1

I would recommend using a promise: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

const loopMyArrayPlease = (array) => { 
  return new Promise(function(resolve, reject) {
    array.forEach((item) => {
        console.log(item) // place holder
        if(!item)
          reject("Unable to do the thing")
    })
    resolve(array);
  });
}

let myArray = ["One", 2, "Three"] // some data here

loopMyArrayPlease(myArray).then(arrayResult => { 
  /** Do some stuff */ 
  console.log(arrayResult)
  process.exit(0)
})
.catch(console.log)
Calvin Ellis
  • 325
  • 2
  • 8
  • 1
    Using Promises is correct, but this won't work. The root problem is that *each* array element triggers asynchronous operations. – Pointy Aug 15 '19 at 23:59