如何重复调用一个异步方法,直到在原生 JavaScript 中获得成功?

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

我有一个异步方法 returns 成功或失败。我必须继续从另一个方法调用这个异步方法,直到我成功为止。但是,如果它反复失败5次,那我就不得不停止调用它了。

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


}
function retry(retries = 5) {
   if (retries < 0) return
   myAsyncApi('/url')
       .then(res => console.log(res))
       .catch(res => retry(retries - 1))
}

如果你想在调用之间有一些延迟,你可以使用 setTimeout 调用重试

重试应该很容易,只需一点递归。基本上如果请求成功,就return。如果失败,则捕获错误并在剩余 1 次尝试后重试。

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