Fetch API 结合 AbortController 实现请求取消与请求超时取消
1. 请求取消
想象一个场景:用户在搜索框中快速输入,每次输入都触发一次请求。我们只关心最后一次请求的结果。使用 AbortController
,实现起来易如反掌。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| let controller;
async function handleSearch(query) { if (controller) { controller.abort(); }
controller = new AbortController(); const signal = controller.signal;
try { const response = await fetch(`/api/search?q=${query}`, { signal }); const data = await response.json(); console.log('Search results:', data); } catch (error) { if (error.name === 'AbortError') { console.log('Fetch aborted'); } else { console.error('Fetch error:', error); } } }
|
3. 请求超时
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| async function fetchWithTimeout(resource, options ={}, timeout = 8000){ const controller = new AbortController(); const id = setTimeout(() => controller.abort(), timeout); const response = await fetch(resource, { ...options, signal: controller.signal }); clearTimeout(id); return response; }
try { const response = await fetchWithTimeout('/api/slow-data', {}, 5000); const data = await response.json(); console.log(data); } catch (error){ if(error.name =='AbortError'){ console.log('Fetch request timed out.'); } }
|