fix: wait for workers exit at worket set stop
authorJérôme Benoit <jerome.benoit@sap.com>
Wed, 5 Jul 2023 16:41:30 +0000 (18:41 +0200)
committerJérôme Benoit <jerome.benoit@sap.com>
Wed, 5 Jul 2023 16:41:30 +0000 (18:41 +0200)
Signed-off-by: Jérôme Benoit <jerome.benoit@sap.com>
src/worker/WorkerSet.ts

index a2e6faf02fbf04063256cbd1533f80f7ce3bef68..d761a12abe2eef9a133781b5c5f8ed1d53f178f8 100644 (file)
@@ -72,7 +72,13 @@ export class WorkerSet extends WorkerAbstract<WorkerData> {
   /** @inheritDoc */
   public async stop(): Promise<void> {
     for (const workerSetElement of this.workerSet) {
+      const workerExitPromise = new Promise<void>((resolve) => {
+        workerSetElement.worker.on('exit', () => {
+          resolve();
+        });
+      });
       await workerSetElement.worker.terminate();
+      await workerExitPromise;
     }
     this.workerSet.clear();
   }
@@ -126,12 +132,18 @@ export class WorkerSet extends WorkerAbstract<WorkerData> {
       'exit',
       this.workerOptions?.poolOptions?.exitHandler ?? WorkerConstants.EMPTY_FUNCTION
     );
-    worker.once('exit', () => this.workerSet.delete(this.getWorkerSetElementByWorker(worker)));
+    worker.once('exit', () =>
+      this.removeWorkerSetElement(this.getWorkerSetElementByWorker(worker))
+    );
     const workerSetElement: WorkerSetElement = { worker, numberOfWorkerElements: 0 };
     this.workerSet.add(workerSetElement);
     return workerSetElement;
   }
 
+  private removeWorkerSetElement(workerSetElement: WorkerSetElement): void {
+    this.workerSet.delete(workerSetElement);
+  }
+
   private async getWorkerSetElement(): Promise<WorkerSetElement> {
     let chosenWorkerSetElement: WorkerSetElement;
     for (const workerSetElement of this.workerSet) {