Skip to content

Commit fbb5232

Browse files
rubiinandywer
andauthored
Document pool task result handling (#343)
* feat: added snippet to for receiving data from pool * Improve task result handling documentation Co-authored-by: Andy Wermke <[email protected]>
1 parent 0154559 commit fbb5232

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

docs/usage-pool.md

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,24 @@ Whenever a pool worker finishes a job, the next pool job is de-queued (that is t
6969

7070
The promise returned by `pool.completed()` will resolve once the scheduled callbacks have been executed and completed. A failing job will make the promise reject. Use `pool.settled()` if you need a promise that resolves without an error even if a task has failed.
7171

72+
## Handling task results
73+
74+
Track a pooled task via the object that the `pool.queue()` promise resolves to. You can `await pool.queue()` to obtain the job's result. Be aware, though, that if you `await` the result directly on queueing, you will only queue another job after this one has finished. You might rather want to `pool.queue().then()` to defer handling the outcome and keep queueing tasks uninterruptedly.
75+
76+
```js
77+
import { spawn, Pool, Worker } from "threads"
78+
79+
const pool = Pool(() => spawn(new Worker("./workers/crytpo")))
80+
const task = pool.queue(crypto => crypto.encrypt("some-password"))
81+
82+
task.then(result => {
83+
// do something with the result
84+
})
85+
86+
await pool.completed()
87+
await pool.terminate()
88+
```
89+
7290
## Cancelling a queued task
7391
7492
You can cancel queued tasks, too. If the pool has already started to execute the task, you cannot cancel it anymore, though.

0 commit comments

Comments
 (0)