我正在实现可中止的获取调用。
在我的页面上中止提取基本上有两个原因:
- 用户决定他/她不想再等待AJAX数据并点击按钮;在这种情况下,UI显示消息";呼叫/任何中断">
- 用户已经移动到页面的另一部分,并且不再需要正在获取的数据;在这种情况下,我不希望UI显示任何内容,因为它只会混淆用户
为了区分这两种情况,我计划使用AbortController.abort
方法的reason
参数,但我的fetch调用中的.catch子句总是接收DOMException('The user aborted a request', ABORT_ERROR)
。
我试图提供一个不同的DOMException
作为情况2中中止的原因,但差异已经丢失。
有人找到如何向fetch.catch子句发送关于中止原因的信息了吗?
在下面的示例中,我演示了如何确定中止fetch
请求的原因。我提供内联评论以供解释。如果有任何不清楚的地方,欢迎发表评论。
重新运行代码片段以查看(可能不同的(随机结果
'use strict';
function delay (ms, value) {
return new Promise(res => setTimeout(() => res(value), ms));
}
function getRandomInt (min = 0, max = 1) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Forward the AbortSignal to fetch:
// https://docs.github.com/en/rest/repos/repos#list-public-repositories
function fetchPublicGHRepos (signal) {
const headers = new Headers([['accept', 'application/vnd.github+json']]);
return fetch('https://api.github.com/repositories', {headers, signal});
}
function example () {
const ac = new AbortController();
const {signal} = ac;
const abortWithReason = (reason) => delay(getRandomInt(1, 5))
.then(() => {
console.log(`Aborting ${signal.aborted ? 'again ' : ''}(reason: ${reason})`);
ac.abort(reason);
});
// Unless GitHub invests HEAVILY into our internet infrastructure,
// one of these promises will resolve before the fetch request
abortWithReason('Reason A');
abortWithReason('Reason B');
fetchPublicGHRepos(signal)
.then(res => console.log(`Fetch succeeded with status: ${res.status}`))
.catch(ex => {
// This is how you can determine if the exception was due to abortion
if (signal.aborted) {
// This is set by the promise which resolved first
// and caused the fetch to abort
const {reason} = signal;
// Use it to guide your logic...
console.log(`Fetch aborted with reason: ${reason}`);
}
else console.log(`Fetch failed with exception: ${ex}`);
});
delay(10).then(() => console.log(`Signal reason: ${signal.reason}`));
}
example();