Skip to content

Instantly share code, notes, and snippets.

@Stuk
Created November 6, 2020 17:35
Show Gist options
  • Select an option

  • Save Stuk/d9c848d26fccae852e726e0279df9177 to your computer and use it in GitHub Desktop.

Select an option

Save Stuk/d9c848d26fccae852e726e0279df9177 to your computer and use it in GitHub Desktop.

Revisions

  1. Stuk created this gist Nov 6, 2020.
    34 changes: 34 additions & 0 deletions example.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,34 @@
    // See https://dom.spec.whatwg.org/#abortcontroller-api-integration

    function getData({signal}) {
    // 1. Let p be a new promise.
    // 4. Return p.
    return new Promise((resolve, reject) => {
    // 2. If options' signal member is present, then:
    if (signal && signal.aborted) {
    // 2. 1. If options' signal's aborted flag is set, then reject p with an "AbortError" DOMException and return p.
    throw new DOMException("Aborted", "AbortError");
    }

    // 3. Run these steps in parallel:
    // 3. 1. Let amazingResult be the result of doing some amazing things.
    const id = setTimeout(() => {
    // 3. 2. Resolve p with amazingResult.
    resolve("data!")
    }, 1000);

    // 2. 2. Add the following abort steps to options’ signal:
    signal && signal.addEventListener("abort", () => {
    // 2. 2. 1. Stop doing amazing things.
    clearTimeout(id);
    // 2. 2. 2. Reject p with an "AbortError" DOMException.
    reject(new DOMException("Aborted", "AbortError"));
    });
    });
    }

    const controller = new AbortController();

    const promise = getData({signal: controller.signal});
    controller.abort();