【问题标题】:AbortController not terminating fetch requestAbortController 未终止获取请求
【发布时间】:2020-02-21 10:21:30
【问题描述】:

我正在尝试创建一个辅助函数以在 2000 毫秒后自动超时 fetch 请求。以下代码不会中止获取请求,而是在 4000 毫秒后正常打印请求。该代码似乎在浏览器中运行,但在节点中不运行。

require('isomorphic-fetch');
const AbortController = require('abort-controller');

const fetchTimeout = async url => {
  const controller = new AbortController();

  setTimeout(() => {
    controller.abort();
  }, 2000);

  return fetch(url, { signal: controller.signal })
    .then(response => {
      return response;
    })
    .catch(error => {
      throw new Error(error.message);
    });
};

const getStock = async () => {
  return await fetchTimeout('https://httpbin.org/delay/4').then(data =>
    data.json()
  );
};

( async () => 
console.log(await getStock())
)();

【问题讨论】:

  • 现在您在编辑后插入了{ signal: controller.signal },代码工作正常。
  • @SebastianSimon 刚刚测试过,它似乎在浏览器中运行良好,但在我最新编辑的包中的 node.js 中却不行。

标签: javascript node.js timeout es6-promise fetch-api


【解决方案1】:

我能够通过使用 node-fetch 库而不是 isomorphic-fetch 来解决此问题,而没有其他实现问题。我已经记录了一张票 here,希望这可以帮助遇到这个令人沮丧的问题的其他人。

【讨论】:

  • 看起来 AbortController 支持“即将”实现同构获取
猜你喜欢
  • 2021-06-18
  • 1970-01-01
  • 1970-01-01
  • 2021-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-11
相关资源
最近更新 更多