Skip to content

Commit aeb9ab4

Browse files
jasnelltargos
authored andcommitted
worker: make Worker async disposable
PR-URL: #58385 Reviewed-By: LiviaMedeiros <livia@cirno.name> Reviewed-By: Anna Henningsen <anna@addaleax.net> Reviewed-By: Matteo Collina <matteo.collina@gmail.com> Reviewed-By: Daeyeon Jeong <daeyeon.dev@gmail.com> Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com>
1 parent e8a07f2 commit aeb9ab4

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
@@ -1861,6 +1861,21 @@ Calling `unref()` on a worker allows the thread to exit if this is the only
18611861
active handle in the event system. If the worker is already `unref()`ed calling
18621862
`unref()` again has no effect.
18631863

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

18661881
### 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)