DEV Community

Cover image for Fetch with AbortController
Mads Stoumann
Mads Stoumann

Posted on

Fetch with AbortController

This is a submission for DEV Challenge v24.03.20, One Byte Explainer: Browser API or Feature.

Explainer

async function go(u,t,o,s=null){try{const r=await fetch(u,
{...o,signal:s});if(!r.ok)throw new Error(`HTTP
error:${r.status}`);return t==='json'?await r.json():
(t==='text'?await r.text():r);}catch(e){throw 
e.name==='AbortError'?new Error('Timeout'):e;}}
Enter fullscreen mode Exit fullscreen mode

Additional Context

Explain fetch() with return type and AbortController in 256 bytes.

The above is 252 bytes — the explaination will be longer 😂

The method has 4 parameters:

  • u (URL)
  • t (return type: 'json', 'text' — or leave blank to get the response)
  • o (options)
  • s (AbortController.signal)

Examples

Basic fetch, return response

const data = await go(
  'https://jsonplaceholder.typicode.com/posts/'
);
Enter fullscreen mode Exit fullscreen mode

Basic fetch, return response as json:

const data = await go(
  'https://jsonplaceholder.typicode.com/posts/',
  'json'
);
Enter fullscreen mode Exit fullscreen mode

Use it with an AbortController, to cancel the fetch() under certain conditions (timeout being the most common):

const controller = new AbortController();
const signal = controller.signal;
const data = await go(
  'https://jsonplaceholder.typicode.com/posts/',
  'json',
  {},
  signal
);
Enter fullscreen mode Exit fullscreen mode

Then, to abort the fetch(), use controller.abort().

In this example, after 5 seconds:

setTimeout(() => controller.abort(), 5000);
Enter fullscreen mode Exit fullscreen mode

Photo by Dapo Abideen

Top comments (0)