Last active
June 4, 2019 16:56
-
-
Save mmun/48eefb38f1379f62a3b286c225526199 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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