Home > Mobile >  How to make requests to an api until have the expected result
How to make requests to an api until have the expected result

Time:01-03

There's a URL with a json. sometimes the data retrieved doesnt has the data that i want, then i would like to request it four more times, till i get the correct result. How can i do this by the right way ? When i call this, the return get really fast.. it fells it isnt making 5 requests, but only one.

I am calling the TryToUpdate function.

const getText = new Promise((resolve, reject) => {
  var retorno;
  fetch('URL').then(i => i.json()).then(i => {
    retorno = i ? .result[0] ? .edited_channel_post ? .text;
    if (retorno.includes('Texto:')) {
      resolve({
        data: retorno,
      });
    } else {
      reject('unavailable');
    }
  })
})

async function tryToUpdate(tries = 0) {
  var retorno;
  var tryNum = tries
  if (tries >= 5) {
    console.log('Cant update.');
    return undefined;
  } else {
    getText
      .then(i => retorno)
      .catch(() => {
        console.log('Cannot reach result. Try num:'   tryNum);
        tryToUpdate(tryNum   1);

      });
  }
}

I tried to make 5 requests to a URL till i get the expected result.

CodePudding user response:

In this revised version of the function, the getText function is called within the while loop, and the loop continues until either retorno is defined (meaning that the getText function resolved successfully) or tries reaches 5 (meaning that the getText function has thrown an error 5 times).

async function tryToUpdate() {
  let retorno;
  let tries = 0;
  while (!retorno && tries < 5) {
    try {
      retorno = await getText();
    } catch (error) {
      console.log(`Cannot reach result. Try num: ${tries}`);
      tries  ;
    }
  }
  if (retorno) {
    console.log(retorno);
  } else {
    console.log('Cannot update.');
  }
}

CodePudding user response:

According to my understanding the problem is a UX problem, that is, it is happening too quickly. You can wait for a while if there was a problem, like:

setTimeout(function() {
    tryToUpdate(tryNum 1);
}, 200);

CodePudding user response:

This can be thought of as a promise chain that's built conditionally. Below, the function tryToUpdate catches errors, pauses and recurses up to 5 times.

// generic pause code
const pause = async (ms) => new Promise(res => setTimeout(res, ms));

// this is the OP's fetch rewritten to demo.  see note below the snippet
function getText(invocation) {
  // pause 100ms, fail on the first few, then succeed
  return pause(100).then(() => {
    if (invocation < 3) throw 'failure';
    return Promise.resolve('success')
  })
}

function tryToUpdate(invocation=0) {
  return getText(invocation).catch(error => {
    if (invocation < 5) {
      console.log('failed, retrying')
      // the OP should select an appropriate pause.
      // no pause might be too fast for the api
      return pause(1000).then(() => tryToUpdate(invocation 1))
    } else {
      console.log('failed, and no more retry')
      throw error
    }
  })
}

tryToUpdate().then(console.log)

The OP's fetch can be improved by not creating a new Promise...

const getText = url => {
  return fetch('URL').then(i => i.json()).then(i => {
    retorno = i?.result[0]?.edited_channel_post?.text;
    return retorno.includes('Texto:') ? { data: retorno } : throw 'unavailable';
  })
}
  • Related