diff --git a/doc/api/worker_threads.md b/doc/api/worker_threads.md index 06b9d488eaff4d..fa6d26a2faee48 100644 --- a/doc/api/worker_threads.md +++ b/doc/api/worker_threads.md @@ -1846,6 +1846,14 @@ 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]()` + + + +Alias for [`worker.terminate()`][]. + ## Notes ### Synchronous blocking of stdio diff --git a/lib/internal/worker.js b/lib/internal/worker.js index 22535cc9bcbf49..b1fe97a5b81285 100644 --- a/lib/internal/worker.js +++ b/lib/internal/worker.js @@ -58,7 +58,7 @@ const { const { createMainThreadPort, destroyMainThreadPort } = require('internal/worker/messaging'); const { deserializeError } = require('internal/error_serdes'); const { fileURLToPath, isURL, pathToFileURL } = require('internal/url'); -const { kEmptyObject } = require('internal/util'); +const { kEmptyObject, SymbolAsyncDispose } = require('internal/util'); const { validateArray, validateString } = require('internal/validators'); const { throwIfBuildingSnapshot, @@ -406,6 +406,10 @@ class Worker extends EventEmitter { }); } + async [SymbolAsyncDispose]() { + await this.terminate(); + } + ref() { if (this[kHandle] === null) return; diff --git a/test/parallel/test-worker-dispose.mjs b/test/parallel/test-worker-dispose.mjs new file mode 100644 index 00000000000000..1c426cc3403f31 --- /dev/null +++ b/test/parallel/test-worker-dispose.mjs @@ -0,0 +1,9 @@ +import * as common from '../common/index.mjs'; +import { Worker } from 'node:worker_threads'; + +{ + // Verifies that the worker is async disposable + const worker = new Worker('for(;;) {}', { eval: true }); + worker.on('exit', common.mustCall()); + await worker[Symbol.asyncDispose](); +}