Skip to content

Instantly share code, notes, and snippets.

@johnborges
Last active January 26, 2021 19:10
Show Gist options
  • Save johnborges/4421a99410f7848ead5d757749a8d6ca to your computer and use it in GitHub Desktop.
Save johnborges/4421a99410f7848ead5d757749a8d6ca to your computer and use it in GitHub Desktop.
Cancel a Fetch Request
const controller = new AbortController();
const { signal } = controller;
fetch("http://localhost:8000", { signal }).then(response => {
console.log(`Request 1 is complete!`);
}).catch(e => {
console.warn(`Fetch 1 error: ${e.message}`);
});
fetch("http://localhost:8000", { signal }).then(response => {
console.log(`Request 2 is complete!`);
if(e.name === "AbortError") {
// We know it's been canceled!
}
}).catch(e => {
console.warn(`Fetch 2 error: ${e.message}`);
if(e.name === "AbortError") {
// We know it's been canceled!
}
});
// Wait 2 seconds to abort both requests
setTimeout(() => controller.abort(), 2000);
// Utility for One Signal Many Fetches
async function fetchStory({ signal } = {}) {
const storyResponse = await fetch('/story.json', { signal });
const data = await storyResponse.json();
const chapterFetches = data.chapterUrls.map(async url => {
const response = await fetch(url, { signal });
return response.text();
});
return Promise.all(chapterFetches);
}
const controller = new AbortController();
const signal = controller.signal;
fetchStory({ signal }).then(chapters => {
console.log(chapters);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment