Search code examples
javascriptnode.jstimeoutes6-promisefetch-api

AbortController not terminating fetch request


I'm attempting to create a helper function to automatically timeout fetch requests after 2000 ms. The following code does not abort the fetch request, and instead prints the request as normal after 4000 ms. 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())
)();

Solution

  • I was able to fix this issue by using the node-fetch library instead of isomorphic-fetch with no other implementation issues. I've logged a ticket here, hope this can help someone else experiencing this frusturating issue.