worker: make Worker async disposable

PR-URL: https://github.com/nodejs/node/pull/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>
This commit is contained in:
James M Snell 2025-05-24 14:03:45 -07:00
parent 62855f3b8c
commit 34c149aa43
2 changed files with 20 additions and 0 deletions

View File

@ -1863,6 +1863,21 @@ Calling `unref()` on a worker allows the thread to exit if this is the only
active handle in the event system. If the worker is already `unref()`ed calling
`unref()` again has no effect.
### `worker[Symbol.asyncDispose]()`
<!-- YAML
added: REPLACEME
-->
Calls [`worker.terminate()`][] when the dispose scope is exited.
```js
async function example() {
await using worker = new Worker('for (;;) {}', { eval: true });
// Worker is automatically terminate when the scope is exited.
}
```
## Notes
### Synchronous blocking of stdio

View File

@ -19,6 +19,7 @@ const {
String,
StringPrototypeTrim,
Symbol,
SymbolAsyncDispose,
SymbolFor,
TypedArrayPrototypeFill,
Uint32Array,
@ -407,6 +408,10 @@ class Worker extends EventEmitter {
});
}
async [SymbolAsyncDispose]() {
await this.terminate();
}
ref() {
if (this[kHandle] === null) return;