简体   繁体   English

AbortController 未终止获取请求

[英]AbortController not terminating fetch request

I'm attempting to create a helper function to automatically timeout fetch requests after 2000 ms.我正在尝试创建一个助手 function 以在 2000 毫秒后自动超时fetch请求。 The following code does not abort the fetch request, and instead prints the request as normal after 4000 ms.以下代码不会中止获取请求,而是在 4000 毫秒后正常打印请求。 The code appears to be working in browser but not in node.该代码似乎在浏览器中运行,但在节点中不起作用。

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

I was able to fix this issue by using the node-fetch library instead of isomorphic-fetch with no other implementation issues.我能够通过使用 node-fetch 库而不是 isomorphic-fetch 来解决这个问题,而没有其他实现问题。 I've logged a ticket here , hope this can help someone else experiencing this frusturating issue.我在 这里记录了一张票,希望这可以帮助其他遇到这个令人沮丧的问题的人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM