Skip to content

Instantly share code, notes, and snippets.

@mmun
Last active June 4, 2019 16:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mmun/48eefb38f1379f62a3b286c225526199 to your computer and use it in GitHub Desktop.
Save mmun/48eefb38f1379f62a3b286c225526199 to your computer and use it in GitHub Desktop.
/*
This is an example of how you would compose two APIs that use AbortController.
The function `getLocalShops` first gets the user's geolocation coordinates
and then makes a fetch using these coordinates. Both of these operations could be expensive,
so we want to abort them as soon as the outer getLocalShops call is aborted.
*/
import { getGeolocation, fetch } from 'abortable-functions';
async function getLocalShops({ signal }) {
const geolocationController = new AbortController();
const geolocationAborter = () => { geolocationController.abort(); };
let myCoords;
try {
signal.addEventListener('abort', geolocationAborter);
myCoords = await getGeolocation({ signal: geolocationController.signal });
} finally {
signal.removeEventListener('abort', geolocationAborter);
}
if (signal.aborted) {
throw new AbortError("getLocalShops aborted");
}
const fetchController = new AbortController();
const fetchAborter = () => { fetchController.abort(); };
let shops;
try {
signal.addEventListener('abort', fetchAborter);
shops = await fetch(`/shops?coords=${myCoords}`, { signal: fetchController.signal });
} finally {
signal.removeEventListener('abort', fetchAborter);
}
if (signal.aborted) {
throw new AbortError("getLocalShops aborted");
}
return shops;
}
// Example
const controller = new AbortController();
getLocalShops({ signal: controller.signal });
await timeout(1000);
controller.abort();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment