Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add signal abort reason #40

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 17 additions & 14 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,34 +9,37 @@ export interface ClearableSignal extends AbortSignal {
*/
export function anySignal (signals: Array<AbortSignal | undefined | null>): ClearableSignal {
const controller = new globalThis.AbortController()
const unsubscribe: Function[] = []

function onAbort (): void {
controller.abort()
function onAbort (reason: Error): void {
controller.abort(reason)

for (const signal of signals) {
if (signal?.removeEventListener != null) {
signal.removeEventListener('abort', onAbort)
}
}
clear()
}

for (const signal of signals) {
if (signal?.aborted === true) {
onAbort()
onAbort(signal.reason)
break
}

if (signal?.addEventListener != null) {
signal.addEventListener('abort', onAbort)
const cb = (): void => {
onAbort(signal.reason)
}
unsubscribe.push(() => {
if (signal?.removeEventListener != null) {
signal.removeEventListener('abort', cb)
}
})
signal.addEventListener('abort', cb)
}
}

function clear (): void {
for (const signal of signals) {
if (signal?.removeEventListener != null) {
signal.removeEventListener('abort', onAbort)
}
}
unsubscribe.forEach(cb => {
cb()
})
}

const signal = controller.signal as ClearableSignal
Expand Down
19 changes: 19 additions & 0 deletions test/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,4 +156,23 @@ describe('any-signal', () => {

setMaxListeners(Infinity, signal)
})

it('should be abort with custom signal reason', async () => {
if (!isNode && !isElectronMain) {
return
}

class TimeoutError extends Error {}
class CancelError extends Error {}

const c1 = new AbortController()
const c2 = new AbortController()

const signal = anySignal([c1.signal, c2.signal])

c1.abort(new TimeoutError('timeout'))
c2.abort(new CancelError('cancel'))
expect(signal.reason instanceof CancelError).to.equal(false)
expect(signal.reason instanceof TimeoutError).to.equal(true)
})
})