From 52b71763f1a1240170e777049a80df0ad14ce496 Mon Sep 17 00:00:00 2001 From: =?utf8?q?J=C3=A9r=C3=B4me=20Benoit?= Date: Thu, 20 Jul 2023 23:16:10 +0200 Subject: [PATCH] refactor: cleanup pool.execute() structure MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Signed-off-by: Jérôme Benoit --- src/pools/abstract-pool.ts | 50 ++++++++++++++++++-------------------- 1 file changed, 24 insertions(+), 26 deletions(-) diff --git a/src/pools/abstract-pool.ts b/src/pools/abstract-pool.ts index d55c3101..77991d7b 100644 --- a/src/pools/abstract-pool.ts +++ b/src/pools/abstract-pool.ts @@ -64,7 +64,7 @@ export abstract class AbstractPool< public readonly emitter?: PoolEmitter /** - * The execution response promise map. + * The task execution response promise map. * * - `key`: The message id of each submitted task. * - `value`: An object that contains the worker, the execution response promise resolve and reject callbacks. @@ -614,37 +614,35 @@ export abstract class AbstractPool< /** @inheritDoc */ public async execute (data?: Data, name?: string): Promise { - const timestamp = performance.now() - const workerNodeKey = this.chooseWorkerNode() - const submittedTask: Task = { - name: name ?? DEFAULT_TASK_NAME, - // eslint-disable-next-line @typescript-eslint/consistent-type-assertions - data: data ?? ({} as Data), - timestamp, - workerId: this.getWorkerInfo(workerNodeKey).id as number, - id: randomUUID() - } - const res = new Promise((resolve, reject) => { + return await new Promise((resolve, reject) => { + const timestamp = performance.now() + const workerNodeKey = this.chooseWorkerNode() + const submittedTask: Task = { + name: name ?? DEFAULT_TASK_NAME, + // eslint-disable-next-line @typescript-eslint/consistent-type-assertions + data: data ?? ({} as Data), + timestamp, + workerId: this.getWorkerInfo(workerNodeKey).id as number, + id: randomUUID() + } this.promiseResponseMap.set(submittedTask.id as string, { resolve, reject, worker: this.workerNodes[workerNodeKey].worker }) + if ( + this.opts.enableTasksQueue === true && + (this.busy || + this.workerNodes[workerNodeKey].usage.tasks.executing >= + ((this.opts.tasksQueueOptions as TasksQueueOptions) + .concurrency as number)) + ) { + this.enqueueTask(workerNodeKey, submittedTask) + } else { + this.executeTask(workerNodeKey, submittedTask) + } + this.checkAndEmitEvents() }) - if ( - this.opts.enableTasksQueue === true && - (this.busy || - this.workerNodes[workerNodeKey].usage.tasks.executing >= - ((this.opts.tasksQueueOptions as TasksQueueOptions) - .concurrency as number)) - ) { - this.enqueueTask(workerNodeKey, submittedTask) - } else { - this.executeTask(workerNodeKey, submittedTask) - } - this.checkAndEmitEvents() - // eslint-disable-next-line @typescript-eslint/return-await - return res } /** @inheritDoc */ -- 2.34.1