JavaScript Fetch with Timeout: A Concise Implementation
async function fetchHTML(url, timeout = 5000) { const controller = new AbortController(); const signal = controller.signal; const timer = setTimeout(() => controller.abort(), timeout);
try { const response = await fetch(url, { signal }); return await response.text(); } catch (error) { throw new Error('Fetch failed'); } finally { clearTimeout(timer); } }
// 调用fetchHTML函数 try { const data = await fetchHTML(url); // 处理返回的数据 } catch (error) { if (error.name === 'AbortError') { return '超时'; } }
原文地址: https://www.cveoy.top/t/topic/lPeZ 著作权归作者所有。请勿转载和采集!