Skip to content

Commit 2515b0f

Browse files
authored
Subscribe to task completion eagerly (#271)
1 parent e0769d6 commit 2515b0f

File tree

1 file changed

+11
-11
lines changed

1 file changed

+11
-11
lines changed

src/master/pool.ts

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import DebugLogger from "debug"
22
import { multicast, Observable, Subject } from "observable-fns"
3-
import { allSettled, SettlementResult } from "../ponyfills"
3+
import { allSettled } from "../ponyfills"
44
import { defaultPoolSize } from "./implementation"
55
import {
66
PoolEvent,
@@ -326,11 +326,17 @@ class WorkerPool<ThreadType extends Thread> implements Pool<ThreadType> {
326326
throw this.initErrors[0]
327327
}
328328

329-
const taskCompleted = () => this.taskCompletion(task.id)
330-
let taskCompletionDotThen: Promise<any>["then"] | undefined
329+
const taskID = this.nextTaskID++
330+
const taskCompletion = this.taskCompletion(taskID)
331+
332+
taskCompletion.catch((error) => {
333+
// Prevent unhandled rejections here as we assume the user will use
334+
// `pool.completed()`, `pool.settled()` or `task.catch()` to handle errors
335+
this.debug(`Task #${taskID} errored:`, error)
336+
})
331337

332338
const task: QueuedTask<ThreadType, any> = {
333-
id: this.nextTaskID++,
339+
id: taskID,
334340
run: taskFunction,
335341
cancel: () => {
336342
if (this.taskQueue.indexOf(task) === -1) return
@@ -340,13 +346,7 @@ class WorkerPool<ThreadType extends Thread> implements Pool<ThreadType> {
340346
taskID: task.id
341347
})
342348
},
343-
get then() {
344-
if (!taskCompletionDotThen) {
345-
const promise = taskCompleted()
346-
taskCompletionDotThen = promise.then.bind(promise)
347-
}
348-
return taskCompletionDotThen
349-
}
349+
then: taskCompletion.then.bind(taskCompletion)
350350
}
351351

352352
if (this.taskQueue.length >= maxQueuedJobs) {

0 commit comments

Comments
 (0)