*
* @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))
if (fn?.constructor.name === 'AsyncFunction') {
this.runInAsyncScope(this.runAsync.bind(this), this, fn, message)
} else {
- this.runInAsyncScope(this.run.bind(this), this, fn, message)
+ this.runInAsyncScope(this.runSync.bind(this), this, fn, message)
}
} else if (message.parent != null) {
// Main worker reference message received
* @param fn - Function that will be executed.
* @param message - Input data for the given function.
*/
- protected run (
+ protected runSync (
fn: WorkerSyncFunction<Data, Response>,
message: MessageValue<Data>
): void {
.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)