*
* @param type - The type of async event.
* @param isMain - Whether this is the main worker or not.
- * @param taskFunctions - Task function(s) processed by the worker when the pool's `execution` function is invoked.
+ * @param taskFunctions - Task function(s) processed by the worker when the pool's `execution` function is invoked. The first function is the default function.
* @param mainWorker - Reference to main worker.
* @param opts - Options for the worker.
*/
this.checkAlive.bind(this)()
}
- this.mainWorker?.on(
- 'message',
- (message: MessageValue<Data, MainWorker>) => {
- this.messageListener(message)
- }
- )
+ this.mainWorker?.on('message', this.messageListener.bind(this))
}
private checkWorkerOptions (opts: WorkerOptions): void {
/**
* Checks if the `taskFunctions` parameter is passed to the constructor.
*
- * @param taskFunctions - The task function(s) that should be defined.
+ * @param taskFunctions - The task function(s) parameter that should be checked.
*/
private checkTaskFunctions (
taskFunctions:
}
this.taskFunctions = new Map<string, WorkerFunction<Data, Response>>()
if (typeof taskFunctions !== 'function') {
+ let firstEntry = true
for (const [name, fn] of Object.entries(taskFunctions)) {
if (typeof fn !== 'function') {
throw new Error(
)
}
this.taskFunctions.set(name, fn.bind(this))
+ if (firstEntry) {
+ this.taskFunctions.set(DEFAULT_FUNCTION_NAME, fn.bind(this))
+ firstEntry = false
+ }
}
} else {
this.taskFunctions.set(DEFAULT_FUNCTION_NAME, taskFunctions.bind(this))
.catch(EMPTY_FUNCTION)
}
+ /**
+ * Gets the task function in the given scope.
+ *
+ * @param name - Name of the function that will be returned.
+ */
private getTaskFunction (name?: string): WorkerFunction<Data, Response> {
name = name ?? DEFAULT_FUNCTION_NAME
const fn = this.taskFunctions.get(name)
/**
* Constructs a new poolifier thread worker.
*
- * @param fn - Function processed by the worker when the pool's `execution` function is invoked.
+ * @param taskFunctions - Task function(s) processed by the worker when the pool's `execution` function is invoked.
* @param opts - Options for the worker.
*/
public constructor (
- fn: WorkerFunction<Data, Response> | TaskFunctions<Data, Response>,
+ taskFunctions:
+ | WorkerFunction<Data, Response>
+ | TaskFunctions<Data, Response>,
opts: WorkerOptions = {}
) {
- super('worker-thread-pool:poolifier', isMainThread, fn, parentPort, opts)
+ super(
+ 'worker-thread-pool:poolifier',
+ isMainThread,
+ taskFunctions,
+ parentPort,
+ opts
+ )
}
/** @inheritDoc */
'./tests/worker-files/cluster/testMultiTasksWorker.js'
)
const data = { n: 10 }
+ const result0 = await pool.execute(data)
+ expect(result0).toBe(false)
const result1 = await pool.execute(data, 'jsonIntegerSerialization')
expect(result1).toBe(false)
const result2 = await pool.execute(data, 'factorial')