-
-
Notifications
You must be signed in to change notification settings - Fork 33k
Closed
Labels
discussIssues opened for discussions and feedbacks.Issues opened for discussions and feedbacks.eventtargetIssues and PRs related to the EventTarget implementation.Issues and PRs related to the EventTarget implementation.
Description
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?
Metadata
Metadata
Assignees
Labels
discussIssues opened for discussions and feedbacks.Issues opened for discussions and feedbacks.eventtargetIssues and PRs related to the EventTarget implementation.Issues and PRs related to the EventTarget implementation.