8

I have a node js script with an async main method. Sometimes the script terminates fine, other times it hangs.

const main = async () => {
    let updates = []
    // ... add a bunch of promises to updates
    await Promise.all(updates)
} 

main()

Does anyone know why this script sometimes might hang? It just doesn't terminate though it appears to have run to completion.

Eric Conner
  • 10,422
  • 6
  • 51
  • 67
  • It's impossible to be certain based on what you provide here, but generally this happens if you fail to resolve or reject all your promises and/or don't call `process.exit()` appropriately. – Paul Oct 17 '18 at 18:34
  • 1
    Yes this happens to me a lot--your async function inherently returns a promise even though nothing is explicitly returned. So if you add `main().then(() => process.exit())` it should always terminate. – axanpi Oct 17 '18 at 19:17

1 Answers1

8

Because your function is async, you need to explicitly terminate it when it finishes:

main().then(() => process.exit())
Todd Chaffee
  • 6,754
  • 32
  • 41