From 8590eb48308a9cebdfec4606935341f235bd9cb0 Mon Sep 17 00:00:00 2001 From: Debadree Chatterjee Date: Tue, 7 Feb 2023 23:13:57 +0530 Subject: [PATCH] lib: add aborted() utility function Fixes: https://github.com/nodejs/node/issues/37220 Refs: https://github.com/nodejs/node/pull/36607 PR-URL: https://github.com/nodejs/node/pull/46494 Reviewed-By: James M Snell Reviewed-By: Matteo Collina Reviewed-By: Benjamin Gruenbaum Reviewed-By: Antoine du Hamel --- doc/api/util.md | 45 +++++++++++++++++++++++ lib/internal/abort_controller.js | 34 ++++++++++++++--- lib/util.js | 3 ++ test/parallel/test-aborted-util.js | 59 ++++++++++++++++++++++++++++++ 4 files changed, 136 insertions(+), 5 deletions(-) create mode 100644 test/parallel/test-aborted-util.js diff --git a/doc/api/util.md b/doc/api/util.md index 71d3a9f32eae47..7318b0e3f76fdc 100644 --- a/doc/api/util.md +++ b/doc/api/util.md @@ -1983,6 +1983,51 @@ const channel = new MessageChannel(); channel.port2.postMessage(signal, [signal]); ``` +## `util.aborted(signal, resource)` + + + +> Stability: 1 - Experimental + +* `signal` {AbortSignal} +* `resource` {Object} Any non-null entity, reference to which is held weakly. +* Returns: {Promise} + +Listens to abort event on the provided `signal` and +returns a promise that is fulfilled when the `signal` is +aborted. If the passed `resource` is garbage collected before the `signal` is +aborted, the returned promise shall remain pending indefinitely. + +```cjs +const { aborted } = require('node:util'); + +const dependent = obtainSomethingAbortable(); + +aborted(dependent.signal, dependent).then(() => { + // Do something when dependent is aborted. +}); + +dependent.on('event', () => { + dependent.abort(); +}); +``` + +```mjs +import { aborted } from 'node:util'; + +const dependent = obtainSomethingAbortable(); + +aborted(dependent.signal, dependent).then(() => { + // Do something when dependent is aborted. +}); + +dependent.on('event', () => { + dependent.abort(); +}); +``` + ## `util.types`