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

折月煮酒 提交于 2021-02-08 07:19:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!