DEV Community

Cover image for Fetch with AbortController
Mads Stoumann
Mads Stoumann

Posted on

5

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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up