Javascript 具有一个信号的多个fetch(),以便全部中止
我看到了另一个答案:Javascript 具有一个信号的多个fetch(),以便全部中止,javascript,fetch,abort,Javascript,Fetch,Abort,我看到了另一个答案: 那么,我可以只用一个信号就中止多个提取请求吗?在我写这个问题的时候,我已经从一位致力于实现中止的先驱那里找到了解决方案 所以,是的,你可以:) 这里有一个简单的例子: async function fetchStory({ signal }={}) { const storyResponse = await fetch('/story.json', { signal }); const data = await storyResponse.json(); co
那么,我可以只用一个信号就中止多个提取请求吗?在我写这个问题的时候,我已经从一位致力于实现中止的先驱那里找到了解决方案 所以,是的,你可以:) 这里有一个简单的例子:
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()将拒绝正在进行的回迁的承诺。我抽象了这个问题的解决方案,并提出了“fetch tx”,fetch transaction,它为所有相关的回迁操作提供了一个单一的中止函数 你可以在这里找到它:
哦,事实上,我最终创建了自己的fetch包装器,它可以让您中止所有的fetch包装器,或者单独中止其中的每一个@OrBachar