在循环中没有得到响应的情况下,如何继续获取网页?
for (el of NodeList) {
const url = el.getAttribute('href')
const res = await fetch(url) //if no response, below code won't execute
const html = await response.text()
const parser = new DOMParser()
const doc = parser.parseFromString(html, 'text/html')
alert('parsed successfully')
}
因此,由于它循环工作并一次发送非常多的请求,即使是网络的一个小而短的问题也会破坏整个过程,我该怎么办?
我想你应该处理网络错误。尝试使用重试机制来执行此操作,如果未收到响应,则尝试再次获取网页。
您可以创建带有两个参数的 fetchWithRetry 函数:要获取的 URL 和最大重试次数(以避免无限循环)。
async function fetchWithRetry(url, numberOfRetries) {
try {
const response = await fetch(url);
const html = await response.text();
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
alert('parsed successfully');
return doc;
} catch (error) {
if (numberOfRetries > 0) {
console.error('Error fetching webpage. Retrying...', error);
return fetchWithRetry(url, numberOfRetries - 1);
} else {
console.error('Error fetching webpage. Maximum retries exceeded.', error);
throw error;
}
}
}
然后,您可以修改代码以使用 fetchWithRetry 函数而不是 fetch 函数。
for (el of NodeList) {
const url = el.getAttribute('href');
const doc = await fetchWithRetry(url, 3);
// Do something with the parsed document
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)