From 49d1b48ce81c9f195830a1a886657de6f2de4ca4 Mon Sep 17 00:00:00 2001 From: =?utf8?q?J=C3=A9r=C3=B4me=20Benoit?= Date: Sun, 2 Jul 2023 22:33:55 +0200 Subject: [PATCH] refactor: factor out async function detection helper MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Signed-off-by: Jérôme Benoit --- src/utils.ts | 12 ++++++++++++ src/worker/abstract-worker.ts | 4 ++-- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/src/utils.ts b/src/utils.ts index 1b657bce..f3952ab1 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -111,3 +111,15 @@ export const isKillBehavior = ( ): value is KB => { return value === killBehavior } + +/** + * Detects whether the given value is an asynchronous function or not. + * + * @param fn - Any value. + * @returns `true` if `fn` was an asynchronous function, otherwise `false`. + */ +export const isAsyncFunction = ( + fn: unknown +): fn is (...args: unknown[]) => Promise => { + return typeof fn === 'function' && fn.constructor.name === 'AsyncFunction' +} diff --git a/src/worker/abstract-worker.ts b/src/worker/abstract-worker.ts index f291c524..7d81a88c 100644 --- a/src/worker/abstract-worker.ts +++ b/src/worker/abstract-worker.ts @@ -7,7 +7,7 @@ import type { TaskPerformance, WorkerStatistics } from '../utility-types' -import { EMPTY_FUNCTION, isPlainObject } from '../utils' +import { EMPTY_FUNCTION, isAsyncFunction, isPlainObject } from '../utils' import { type KillBehavior, KillBehaviors, @@ -154,7 +154,7 @@ export abstract class AbstractWorker< if (message.id != null && message.data != null) { // Task message received const fn = this.getTaskFunction(message.name) - if (fn?.constructor.name === 'AsyncFunction') { + if (isAsyncFunction(fn)) { this.runInAsyncScope(this.runAsync.bind(this), this, fn, message) } else { this.runInAsyncScope(this.runSync.bind(this), this, fn, message) -- 2.34.1