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;}}
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/'
);
Basic fetch
, return response
as json
:
const data = await go(
'https://jsonplaceholder.typicode.com/posts/',
'json'
);
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
);
Then, to abort the fetch()
, use controller.abort()
.
In this example, after 5 seconds:
setTimeout(() => controller.abort(), 5000);
Top comments (0)