8

A file deadlock.mjs with this in it:

await new Promise(function(resolve) {});

will run and immediately end giving an exit code of 13. I would've expected this program to hang forever.

await new Promise(function(resolve) {resolve()});

unsurprisingly ends immediately and gives a 0 exit code.

Why doesn't the first program deadlock? And what is the significance of exit code 13?

johncs
  • 163
  • 2
  • 8
  • Unresolved promises by themselves do NOT keep nodejs from exiting. nodejs waits for sockets, files, timers, etc... but does not wait for a promise all by itself. – jfriend00 Oct 30 '20 at 06:16

1 Answers1

7

Node isn't deadlocking because it's noticing that it's not waiting on anything. Here's a great explanation of how it notices that. But because you've used a top-level await here, Node knows that it's exiting abnormally and gives a 13 exit code:

13 Unfinished Top-Level Await: await was used outside of a function in the top-level code, but the passed Promise never resolved.

https://nodejs.org/api/process.html#exit-codes

Nick McCurdy
  • 17,658
  • 5
  • 50
  • 82
johncs
  • 163
  • 2
  • 8
  • I didn't dive deeply into why 13 is the exit code, rather than 1 (which is what node normally uses when the program dies due to an error). But the weird exit code is the main reason I made this question: 13 isn't mentioned _anywhere_ that I could find. So I'm making this a community wiki because hopefully someone will be able to share more. – johncs Oct 30 '20 at 02:56
  • In my case, I oddly had to explicitly exit with `process.exit(0)` (with a top-level `await`; on Node 14.15.5), I'm guessing because the `await` situation was setting `process.exitCode` (which can override the default of `0`). – Brett Zamir Jun 12 '21 at 07:48
  • 1
    Updated the answer with the docs on exit code 13. – Nick McCurdy Oct 16 '22 at 12:40