如何重复调用异步方法,直到您在本机javascript中获得成功?

时间:2019-07-18 16:23:51

标签: javascript async-await es6-promise

  

可以说,我有一个异步方法,它返回成功或失败。我必须不断从另一个方法调用此异步方法,直到获得成功。但是,如果它连续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


}

2 个答案:

答案 0 :(得分:2)

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

如果您希望通话之间有一些延迟,可以使用setTimeout拨打重试电话

答案 1 :(得分:1)

只需稍作递归即可重试。基本上,如果请求成功,则返回。如果失败,则捕获该错误,然后再尝试少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));