问题
I saw this other answer: https://stackoverflow.com/a/47250621/2809729
So can I abort multiple fetch request using just one signal?
回答1:
At the time I was writing the question, I already found the solution in this post on how to abort fetches from one of the pioneers that were working to the implementation of an abort.
So yes you can :) Here a brief example:
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);
}
In the above example, the same signal is used for the initial fetch, and for the parallel chapter fetches. Here's how you'd use fetchStory:
const controller = new AbortController();
const signal = controller.signal;
fetchStory({ signal }).then(chapters => {
console.log(chapters);
});
In this case, calling controller.abort() will reject the promise of the in-progress fetches.
回答2:
I abstracted the solution to this problem, and came up with "fetch-tx", fetch transaction, which provides a single abort function to all related fetch operations.
you can find it here: fetch-tx
来源:https://stackoverflow.com/questions/48998013/multiple-fetch-with-one-signal-in-order-to-abort-them-all