一个信号有多个fetch()以便中止所有信号 [英] Multiple fetch() with one signal in order to abort them all
问题描述
我看到了另一个答案: https://stackoverflow.com/a/47250621/2809729
I saw this other answer: https://stackoverflow.com/a/47250621/2809729
那么我可以仅使用一个信号来中止多个获取请求吗?
So can I abort multiple fetch request using just one signal?
推荐答案
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);
}
在上面的示例中,相同的信号用于初始读取和并行章节读取.这是使用fetchStory的方法:
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);
});
在这种情况下,调用controller.abort()将拒绝正在进行的提取的承诺.
In this case, calling controller.abort() will reject the promise of the in-progress fetches.
这篇关于一个信号有多个fetch()以便中止所有信号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!