6

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

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

VLAZ
  • 26,331
  • 9
  • 49
  • 67
Giacomo Cerquone
  • 2,352
  • 5
  • 24
  • 33

2 Answers2

5

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.

Giacomo Cerquone
  • 2,352
  • 5
  • 24
  • 33
1

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

dudi harush
  • 879
  • 6
  • 5
  • oh well, actually I ended up creating my own fetch wrapper that lets you abort all of them or singularly each one of them https://giacomocerquone.com/blog/fetch-wrapper @OrBachar – Giacomo Cerquone Jan 09 '20 at 10:26