From: Jérôme Benoit Date: Sun, 2 Jul 2023 20:33:55 +0000 (+0200) Subject: refactor: factor out async function detection helper X-Git-Tag: v2.6.7~12 X-Git-Url: https://git.piment-noir.org/?a=commitdiff_plain;h=49d1b48ce81c9f195830a1a886657de6f2de4ca4;p=poolifier.git refactor: factor out async function detection helper Signed-off-by: Jérôme Benoit --- 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)