我正在执行abortable fetch calls.

在我的页面上中止抓取主要有两个原因:

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

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

我试图提供不同的DOMException作为 case 2中中止的原因,但差异消失了.

是否有人找到了如何将信息发送到fetch.catch子句以了解中止的原因?

推荐答案

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

重新运行代码段以查看(可能不同的)随机结果

'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相关问答推荐

Fastify错误:CORS策略已阻止从起源api-dev.example.com上的MLhttp请求

当在select中 Select 选项时,我必须禁用不匹配的 Select

使用axios.获取实时服务器时的404响应

Bootstrap动态选项卡在切换选项卡后保持活动状态,导致元素堆叠

Angular中计算信号和getter的区别

Angular:动画不启动

在grafana情节,避免冲突的情节和传说

你怎么看啦啦队的回应?

如何控制Reaction路由加载器中的错误状态?

本地库中的chartjs-4.4.2和chartjs-plugin-注解

Web Crypto API解密失败,RSA-OAEP

Angular 形式,从DOM中删除不会删除指定索引处的内容,但会删除最后一项

如何在FastAPI中为通过file:/URL加载的本地HTML文件启用CORS?

将对象推送到数组会导致复制

在Odoo中如何以编程方式在POS中添加产品

WebSocketException:远程方在未完成关闭握手的情况下关闭了WebSocket连接.&#三十九岁;

如何根据查询结果重新排列日期

如何在尚未创建的鼠标悬停事件上访问和着色div?

如何让SVG图标在被点击和访问后改变 colored颜色 ,并在被访问后取消点击时恢复到原来的 colored颜色 ?

在单击按钮时生成多个表单时的处理状态