Skip to content

Commit 34c149a

Browse files
committed
worker: make Worker async disposable
PR-URL: #58385 Reviewed-By: LiviaMedeiros <[email protected]> Reviewed-By: Anna Henningsen <[email protected]> Reviewed-By: Matteo Collina <[email protected]> Reviewed-By: Daeyeon Jeong <[email protected]> Reviewed-By: Yagiz Nizipli <[email protected]>
1 parent 62855f3 commit 34c149a

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

doc/api/worker_threads.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1863,6 +1863,21 @@ Calling `unref()` on a worker allows the thread to exit if this is the only
18631863
active handle in the event system. If the worker is already `unref()`ed calling
18641864
`unref()` again has no effect.
18651865

1866+
### `worker[Symbol.asyncDispose]()`
1867+
1868+
<!-- YAML
1869+
added: REPLACEME
1870+
-->
1871+
1872+
Calls [`worker.terminate()`][] when the dispose scope is exited.
1873+
1874+
```js
1875+
async function example() {
1876+
await using worker = new Worker('for (;;) {}', { eval: true });
1877+
// Worker is automatically terminate when the scope is exited.
1878+
}
1879+
```
1880+
18661881
## Notes
18671882

18681883
### Synchronous blocking of stdio

lib/internal/worker.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ const {
1919
String,
2020
StringPrototypeTrim,
2121
Symbol,
22+
SymbolAsyncDispose,
2223
SymbolFor,
2324
TypedArrayPrototypeFill,
2425
Uint32Array,
@@ -407,6 +408,10 @@ class Worker extends EventEmitter {
407408
});
408409
}
409410

411+
async [SymbolAsyncDispose]() {
412+
await this.terminate();
413+
}
414+
410415
ref() {
411416
if (this[kHandle] === null) return;
412417

0 commit comments

Comments
 (0)