Sub topic 3
Cancelling Requests and Adding Timeouts
This chapter assumes you know async/await, try/catch, and the response.ok check from earlier chapters. Top-level await in these examples requires an ES module or the browser console.
Cancelling and Timeouts
You cancel a fetch by passing an AbortSignal in the signal option. AbortSignal.timeout(ms) makes the fetch reject with a TimeoutError once the deadline passes. When you call controller.abort(), the fetch rejects with an AbortError.
const controller = new AbortController();
fetch('https://api.example.com/search?q=fetch', { signal: controller.signal })
.catch((err) => console.log(err.name)); // 'AbortError'
controller.abort();
try {
await fetch('https://api.example.com/slow', { signal: AbortSignal.timeout(3000) });
} catch (err) {
if (err.name === 'TimeoutError') console.log('Gave up after 3 s');
}Running Requests in Parallel
If you start every request before awaiting any of them, they run at the same time. Promise.all rejects as soon as one request fails. Promise.allSettled waits for all of them and reports each result separately.
const urls = ['https://api.example.com/users', 'https://api.example.com/posts'];
const results = await Promise.allSettled(
urls.map(async (url) => {
const res = await fetch(url);
if (!res.ok) throw new Error(`${url}: HTTP ${res.status}`);
return res.json();
})
);
results.forEach((r) => console.log(r.status, r.value ?? r.reason.message));CORS and Cookies
By default, the browser does not send cookies on cross-origin requests. Set credentials: 'include' to send them. The server must then reply with Access-Control-Allow-Credentials: true and a specific Access-Control-Allow-Origin value, not *.
Streaming Large Responses
response.body is a ReadableStream. You can read it chunk by chunk to report progress:
const res = await fetch('https://api.example.com/big.txt');
const reader = res.body.getReader();
let received = 0;
while (true) {
const { done, value } = await reader.read();
if (done) break;
received += value.length;
console.log(`Received ${received} bytes`);
}A Reusable Helper
A wrapper puts the timeout, JSON encoding, and error checks in one place.
async function request(url, { json, timeout = 10000, ...options } = {}) {
const init = { ...options, signal: options.signal ?? AbortSignal.timeout(timeout) };
if (json !== undefined) {
init.body = JSON.stringify(json);
init.headers = { 'Content-Type': 'application/json', ...options.headers };
}
const res = await fetch(url, init);
if (!res.ok) throw new Error(`HTTP ${res.status} ${res.statusText}`);
return res.status === 204 ? null : res.json();
}
const user = await request('https://api.example.com/users', {
method: 'POST',
json: { name: 'Ada' }
});Exercise
You load three dashboard widgets at once and want to show whichever ones succeed, even if one API returns 500. Should you use Promise.all or Promise.allSettled, and why?
Show answer
Use Promise.allSettled. Promise.all rejects on the first failure and you lose the other results. allSettled gives a fulfilled or rejected entry for each request, so you can show the widgets that loaded.