gpt4 book ai didi

javascript - AbortController.abort(reason),但原因在到达 fetch catch 子句之前就丢失了

转载 作者:行者123 更新时间:2023-12-05 03:21:01 26 4
gpt4 key购买 nike

我正在实现 abortable fetch calls .

在我的页面上中止提取基本上有两个原因:

  • 用户决定他/她不想再等待 AJAX 数据并点击一个按钮;在这种情况下,用户界面会显示一条消息“调用/任何中断”
  • 用户已经移动到页面的另一部分并且不再需要正在获取的数据;在这种情况下,我不希望 UI 显示任何内容,因为它只会让用户感到困惑

为了区分这两种情况,我计划使用 AbortController.abort 方法的 reason 参数,但我的 fetch 调用中的 .catch 子句总是收到DOMException('用户中止请求', ABORT_ERROR)

我尝试提供不同的 DOMException作为案例 2 中止的原因,但差异丢失了。

有没有人找到如何将有关中止原因的信息发送到 fetch .catch 子句?

最佳答案

在下面的示例中,我演示了如何确定 fetch 请求中止的原因。我提供内联评论以供解释。如果有任何不清楚的地方,请随时发表评论。

Re-run the code snippet to see a (potentially different) random result

'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();

关于javascript - AbortController.abort(reason),但原因在到达 fetch catch 子句之前就丢失了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73049849/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com