diff options
author | Kitson Kelly <me@kitsonkelly.com> | 2020-04-16 00:10:49 +1000 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-04-15 10:10:49 -0400 |
commit | cb64cf3ce2ea46883fa8bc2b4242dfd07e4551e5 (patch) | |
tree | 0eeae9e1d2e5e190804cf362968be0688a161910 /cli/js/web/abort_signal.ts | |
parent | 95eb6d780c2790b524dc3ad6f21958260c2dadfe (diff) |
Add support for AbortController/AbortSignal (#4757)
Diffstat (limited to 'cli/js/web/abort_signal.ts')
-rw-r--r-- | cli/js/web/abort_signal.ts | 58 |
1 files changed, 58 insertions, 0 deletions
diff --git a/cli/js/web/abort_signal.ts b/cli/js/web/abort_signal.ts new file mode 100644 index 000000000..b741d6534 --- /dev/null +++ b/cli/js/web/abort_signal.ts @@ -0,0 +1,58 @@ +// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license. +import { EventImpl } from "./event.ts"; +import { EventTargetImpl } from "./event_target.ts"; + +export const add = Symbol("add"); +export const signalAbort = Symbol("signalAbort"); +export const remove = Symbol("remove"); + +export class AbortSignalImpl extends EventTargetImpl implements AbortSignal { + #aborted?: boolean; + #abortAlgorithms = new Set<() => void>(); + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + onabort: ((this: AbortSignal, ev: Event) => any) | null = null; + + [add](algorithm: () => void): void { + this.#abortAlgorithms.add(algorithm); + } + + [signalAbort](): void { + if (this.#aborted) { + return; + } + this.#aborted = true; + for (const algorithm of this.#abortAlgorithms) { + algorithm(); + } + this.#abortAlgorithms.clear(); + this.dispatchEvent(new EventImpl("abort")); + } + + [remove](algorithm: () => void): void { + this.#abortAlgorithms.delete(algorithm); + } + + constructor() { + super(); + this.addEventListener("abort", (evt: Event) => { + const { onabort } = this; + if (typeof onabort === "function") { + onabort.call(this, evt); + } + }); + } + + get aborted(): boolean { + return Boolean(this.#aborted); + } + + get [Symbol.toStringTag](): string { + return "AbortSignal"; + } +} + +Object.defineProperty(AbortSignalImpl, "name", { + value: "AbortSignal", + configurable: true, +}); |