Skip to content

Commit

Permalink
signal; helpers
Browse files Browse the repository at this point in the history
  • Loading branch information
samthor committed Oct 23, 2023
1 parent 4c49570 commit 8ea9f7e
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 4 deletions.
36 changes: 35 additions & 1 deletion src/signal.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

/**
* Ensures that a passed {@link Function} is called when the given {@link AbortSignal} is aborted.
*
Expand All @@ -11,3 +10,38 @@ export function handleAbortSignalAbort(signal: AbortSignal | undefined, fn: () =
signal?.addEventListener('abort', fn);
}
}

/**
* Returns a {@link Promise} for the abort of the passed {@link AbortSignal}. This may be
* immediately.
*/
export function promiseForSignal<T = never>(
signal: AbortSignal,
resolveWith: Promise<T> | T = Promise.reject<T>(new Error('aborted')),
): Promise<T> {
if (signal.aborted) {
return Promise.resolve(resolveWith);
} else {
return new Promise((resolve) => {
signal.addEventListener('abort', () => resolve(resolveWith));
});
}
}

/**
* Returns a new {@link AbortSignal} that can be individually aborted, but which is also tied to
* the lifetime of the passed signal.
*
* If the passed signal is already aborted, returns it directly.
*/
export function derivedSignal(previous?: AbortSignal) {
if (previous?.aborted) {
return { signal: previous, abort: () => {} };
}

const c = new AbortController();
const abort = () => c.abort();

previous?.addEventListener('abort', abort);
return { signal: c.signal, abort };
}
6 changes: 3 additions & 3 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@

// if you'd like to warn if you're using modern features, change these
// both to e.g., "es2017"
"module": "esnext",
"target": "esnext",
"moduleResolution": "nodenext",
"module": "NodeNext",
"target": "ESNext",
"moduleResolution": "NodeNext",
"esModuleInterop": true,

"allowSyntheticDefaultImports": true,
Expand Down

0 comments on commit 8ea9f7e

Please sign in to comment.