我正在实施可中止的获取调用 https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort.
中止我的页面上的提取基本上有两个原因:
- 用户决定不再等待 AJAX 数据并单击按钮;在这种情况下,用户界面会显示一条消息“呼叫/任何中断”
- 用户已移动到页面的另一部分,并且不再需要正在获取的数据;在这种情况下,我不希望用户界面显示任何内容,因为它只会让用户感到困惑
为了区分这两种情况,我打算使用reason
的参数AbortController.abort
方法,但我的 fetch 调用中的 .catch 子句总是收到一个DOMException('The user aborted a request', ABORT_ERROR)
.
我试图提供一个不同的DOMException https://webidl.spec.whatwg.org/#idl-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();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)