Skip to content

Instantly share code, notes, and snippets.

@Stuk
Created November 6, 2020 17:35
Show Gist options
  • Save Stuk/d9c848d26fccae852e726e0279df9177 to your computer and use it in GitHub Desktop.
Save Stuk/d9c848d26fccae852e726e0279df9177 to your computer and use it in GitHub Desktop.
AbortController usage
// 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();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment