我需要无限循环地从服务器获取数据。 此代码生成递归,这是正确的方法吗?
我的代码:
function pause(delay) { return new Promise(r => setTimeout(r, delay)) }
async function fetchData( url, tries = 5 ) {
try {
const response = await fetch(url);
if ( !response.ok )
throw new Error('Request error');
const contentType = response.headers.get('content-type');
if ( !contentType || !contentType.includes('application/json'))
throw new TypeError('not a JSON')
const jsonData = await response.json();
return jsonData;
} catch(err) {
console.error('catch error:', err, 'tries left', tries);
if ( tries == 0 ) throw new Error(err);
pause(1500).then( () => fetchData( url, tries - 1 ) );
}
}
function infinityLoop() {
fetchData('test.json').then(d => {console.log(d); pause(1000).then( infinityLoop ); });
}
infinityLoop();
在您的代码中,如果出现故障,则 fetchData 将返回未定义,因为您没有返回任何内容
试试这个
function pause(delay) {
return new Promise(r => setTimeout(r, delay))
}
async function fetchData(url, tries = 5) {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error('Request error');
}
const contentType = response.headers.get('content-type');
if (!contentType || !contentType.includes('application/json')) {
throw new TypeError('not a JSON')
}
const jsonData = await response.json();
return jsonData;
} catch (err) {
console.error('catch error:', err, 'tries left', tries);
if (tries == 0) {
throw new Error(err);
}
await pause(1500);
return fetchData(url, tries - 1);
}
}
您忘记在
fetchData()
内的 infinityLoop()
前面放置一个等待修饰符,之后您只需要使该函数也异步即可。