diff --git a/packages/cli-repl/src/mongosh-repl.ts b/packages/cli-repl/src/mongosh-repl.ts index 27813995d..883317b5e 100644 --- a/packages/cli-repl/src/mongosh-repl.ts +++ b/packages/cli-repl/src/mongosh-repl.ts @@ -127,6 +127,7 @@ type Mutable = { class MongoshNodeRepl implements EvaluationListener { _runtimeState: MongoshRuntimeState | null; closeTrace?: string; + exitPromise?: Promise; input: Readable; lineByLineInput: LineByLineInput; output: Writable; @@ -545,6 +546,7 @@ class MongoshNodeRepl implements EvaluationListener { }); repl.on('exit', () => { + if (this._runtimeState) this._runtimeState.repl = null; this.onExit().catch(() => { /* ... */ }); @@ -1051,7 +1053,10 @@ class MongoshNodeRepl implements EvaluationListener { if (rs) { this._runtimeState = null; this.closeTrace = new Error().stack; - rs.repl?.close(); + if (rs.repl) { + rs.repl.close(); + await once(rs.repl, 'exit'); + } await rs.instanceState.close(true); await new Promise((resolve) => this.output.write('', resolve)); } @@ -1063,8 +1068,10 @@ class MongoshNodeRepl implements EvaluationListener { * @param exitCode The user-specified exit code, if any. */ async onExit(exitCode?: number): Promise { - await this.close(); - return this.ioProvider.exit(exitCode); + return (this.exitPromise ??= (async () => { + await this.close(); + return this.ioProvider.exit(exitCode); + })()); } /**