我看到了另一个答案:https://stackoverflow.com/a/47250621/2809729
那么我可以仅使用一个信号中止多个获取请求吗?
在我写这个问题的时候,我已经找到了this post on how to abort fetches的解决方案,这个解决方案来自致力于实施中止的先驱之一。
所以是的,你可以:)这里有一个简短的例子:
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:
const controller = new AbortController();
const signal = controller.signal;
fetchStory({ signal }).then(chapters => {
console.log(chapters);
});
在这种情况下,调用controller.abort()将拒绝正在进行的提取的承诺。