Search code examples
javascriptasync-awaites6-promise

How to call a async method repeatedly until you get success in native JavaScript?


I have an async method which returns either success or fail. I have to keep calling this async method from another method until I get success. But if it fails repeatedly for 5 times then I have to stop calling it.

let count = 0;

function myAsyncApi(url){
  
   //this is a fake async method which return success at certain point of time
  
     return new Promise((resolve, reject) => {
      if(count === 5){
        setTimeout(function(){
            resolve('succes')
        }, 100);
      }
      else{
        setTimeout(function(){
            reject('failure');
        }, 100);          
      }
      
      count++;
  });
}

function retry(){
  // I have to call myAsyncApi('/url') from this function repeatedly
  // Whenever we get success from myAsyncApi(url) we have to stop calling the API
  // if we get fail then call myAsyncApi('/url') again until count reaches 5

 // how can we achieve this without using async/await in this function


}

Solution

  • Retrying should be pretty easy with a little recursion. Basically if the request succeeds, just return. If it fails, otherwise catch the error and try again with 1 less attempt remaining.

    function fetchAndRetry(retryAttempts = 5) {
      if (retryAttempts < 0) {
          return Promise.reject(new Error("Exceeded maximum retries fetching /url"));
      }
      console.log("Attempting, " + retryAttempts + " attempts left.");
      return myAsyncApi('/url').catch(() => fetchAndRetry(retryAttempts - 1));
    }
    
    fetchAndRetry().then(res => console.log(res));