DEV Community

Discussion on: Fetch-22

Collapse
 
aminnairi profile image
Amin

Hi there, very interesting topic, thanks for this library!

You can use a combination of setTimeout, AbortController and the Fetch API to achieve a similar result, while still leveraging the power of promises.

const createSignalWithTimeout = (seconds) => {
  const milliseconds = seconds * 1000;
  const abortController = new AbortController();
  const signal = abortController.signal;

  let timeout = null;

  timeout = window.setTimeout(abortController.abort, milliseconds);

  const cancelSignal = () => {
    window.clearTimeout(timeout);
  };

  return { cancelSignal, signal };
};

const { signal, cancelSignal } = createSignalWithTimeout(1);

fetch("https://jsonplaceholder.typicode.com/users", { signal }).then((response) => {
  if (response.ok) {
    cancelSignal();
    return response.json();
  }

  throw new Error("Bad response from the server");
}).then((users) => {
  console.log(users);
}).catch(({ message }) => {
  console.error(message);
});
Enter fullscreen mode Exit fullscreen mode

This is a very great use-case for using this obscure AbortController. Although you don't really manage what error message is thrown, you can still detect the instanceof the error which will be AbortError in that case. See MDN.

Collapse
 
madsstoumann profile image
Mads Stoumann • Edited

It's exactly what I'm using, if you look at the code - it just adds the AbortError to the same errorHandler.
The result is a promise ;-)

  /* Handle timeout / AbortController */
  if ('AbortController' in window) {
    const controller = new AbortController();
    const signal = controller.signal;
    settings.signal = signal;
    setTimeout(() => {return controller.abort()}, timeout);
  }
Enter fullscreen mode Exit fullscreen mode
Collapse
 
aminnairi profile image
Amin • Edited

You are correct, I didn't look at your code, very well done then!

I'll let this code snippet for people wanting an alternative without the start/stop callback or the error list.

Thread Thread
 
madsstoumann profile image
Mads Stoumann

👍