'Multiple fetch() with one signal in order to abort them all

I saw this other answer: https://stackoverflow.com/a/47250621/2809729

So can I abort multiple fetch request using just one signal?



Solution 1:[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.

Solution 2:[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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2