Skip to content

Add a utility for knowing an AbortSignal was aborted #37220

Description

@benjamingr

Hey,

Speaking to library authors in the ecosystem it appears that this pattern of code is very common (also in our code):

if (signal.aborted) {
  // cleanup
} else {
  const listener = (err) => {
    // cleanup  
  };
  signal.addEventListener('abort', listener);
  resource.on('done', () => signal.removeEventListener('abort', listener);
}

It would be very useful to be able to write this code in a more ergonomic way, talking to @getify about this in the CAF repo a utility was suggested:

const { once } = require('events');

// returns a promise for when the signal was aborted
async function aborted(signal, resource = null) {
  if (signal.aborted) return; // early return on aborted signal
  // the kWeak bit not implemented yet is so that the event listener doesn't leak
  await once(signal, "abort", { [kWeak]: resource });
}

Which would let you do

await aborted(signal);
// Or
// or some other resource, when the request gets GCd the listener gets removed automatically
await aborted(signal, request);

Any opinions on this? (Personally I am in favour) If we add such an API under what module would it live?

cc @jasnell @addaleax ?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    discussIssues opened for discussion and feedback.eventtargetIssues and PRs related to the EventTarget implementation.

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions