Async/Await Syntax
What improvement does this pattern offer over the Promise.race timeout pattern?
async function fetchWithTimeout(url, ms) {
const controller = new AbortController();
const id = setTimeout(() => controller.abort(), ms);
try {
const response = await fetch(url, { signal: controller.signal });
clearTimeout(id);
return response;
} catch (error) {
clearTimeout(id);
if (error.name === 'AbortError') {
throw new Error('Request timed out');
}
throw error;
}
}