首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >AbortController.abort(原因),但是这个原因在到达fetch子句之前就丢失了

AbortController.abort(原因),但是这个原因在到达fetch子句之前就丢失了
EN

Stack Overflow用户
提问于 2022-07-20 10:18:20
回答 1查看 401关注 0票数 2

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

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

  • 用户决定不再等待AJAX数据,并单击一个按钮;在本例中,UI显示一条消息“调用/whatever中断”。
  • 用户已移动到页面的另一部分,不再需要正在获取的数据;在本例中,我不希望UI显示任何内容,因为这只会使用户感到困惑

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

在第2种情况下,我尝试提供一个不同的DOMException作为中止的原因,但是差异消失了。

是否有人发现如何向fetch .catch子句发送有关中止原因的信息?

EN

Stack Overflow用户

回答已采纳

发布于 2022-07-20 10:44:25

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

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

代码语言:javascript
运行
复制
'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();

票数 2
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73049849

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档