Retry on promises

Hey guys
Sometimes when trying to send a call to a smart contract using tronWeb I get an error. Please take a look at this simple snippet that calls the getPlayer method from the contract:

async function getPlayer(adrs) {
    await contract.getPlayer(adrs).call((err, res) => {
        if(!err) { console.log(res); }
        else { console.log(err); }
    });
}

What is the best practice to build a ‘retry’ method on catching error?
I have tried while loops and also tried setInterval() with a retry limit. But i didnt find them reliable enough.

Hi Hesam,

The simplest way to build a retry with async is as follows:


function delay(timeout) {
  return new Promise(resolve => setTimeout(resolve, timeout));
}

async function getPlayer(adrs) {

  let retryCount = 0;
  while (retryCount++ < 5) {
    try {
      // Function will return if call was done succesfully
      return await contract.getPlayer(adrs).call();
    } catch (e) {
      // Error is catched and the next while loop is triggered
      console.error(e);
    }

    // Wait for 1 second before retrying
    await delay(1000);
  }
}
1 Like