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

Mar*_*lli 4 javascript google-chrome domexception fetch-api abortcontroller

我正在实施可中止的获取调用

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

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

为了区分这两种情况,我计划使用reason该方法的参数AbortController.abort,但 fetch 调用中的 .catch 子句始终收到一个DOMException('The user aborted a request', ABORT_ERROR).

我试图提供一个不同的DOMException作为情况 2 中止的原因,但差异丢失了。

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

jse*_*ksn 6

在下面的示例中,我演示了如何确定请求中止的原因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();
Run Code Online (Sandbox Code Playgroud)