skip to Main Content

I need to fetch data from server in infinity loop.
This code generates a reursion, is this correct way?

My code (code updated):

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 );
  }
}

function infinityLoop() {
  fetchData('test.json').then(d => {console.log(d); pause(1000).then( infinityLoop ); });
}
infinityLoop();

updated suggestion (by Dimava), that replace recursion with loop

await function infinityLoop() {
    while ( true ) {
        try {
            let d = await fetchData('test.json');
            console.log(d);
            await pause(1000);
        } catch ( err ) {
            console.error('error:', err);
            break;
        }
    }
    return 0;
}
infinityLoop();

2

Answers


  1. You forgot to put a await modifier infront of the fetchData() within the infinityLoop() after that you only need to make the function async aswell.

    Login or Signup to reply.
  2. If you want to make an async loop, make an async loop

    async function asyncLoop() {
      while(true) {
        let data = await fetchData('test.json');
        await pause(1000)
      }
    }
    asyncLoop();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search