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

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay