Skip to content

Example of aborting fetch with an AbortController and CancellationToken#104

Open
kjvalencik wants to merge 1 commit into
mainfrom
kv/fetch-abort
Open

Example of aborting fetch with an AbortController and CancellationToken#104
kjvalencik wants to merge 1 commit into
mainfrom
kv/fetch-abort

Conversation

@kjvalencik

Copy link
Copy Markdown
Member

Example of adapting a JavaScript AbortController to a tokio CancellationToken.

TODO: Include docs on how this works.

Usage

# default 1s timeout
$ node test.js
2026-03-03

# short timeout
$ node test.js 10
[Error: Request aborted]


const timeout = Number(process.argv[2]) || 10000;

async function main() {

@vadimpiven vadimpiven Jun 8, 2026

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe this should be

async function callAbortable<T>(
  callback: (token: CancellationToken) => Promise<T>,
  signal: AbortSignal,
): Promise<T> {
  const token = new CancellationToken();
  const abort = () => token.cancel();
  try {
    signal.addEventListener('abort', abort, { once: true });
    signal.throwIfAborted();
    return await callback(token);
  } finally {
    signal.removeEventListener('abort', abort);
  }
}

async function main() {
  const version = process.version;
  const date = await callAbortable(
    (token) => nodeReleaseDateWithAbort(version, token),
    AbortSignal.timeout(timeout),
  );
  console.log(date);
}

to avoid calling addon if the signal is already aborted and clean-up listener to avoid memory leaks

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants