首页 > 解决方案 > 如何重复调用异步方法,直到在原生 JavaScript 中获得成功?

问题描述

我有一个返回成功或失败的异步方法。我必须继续从另一个方法调用这个异步方法,直到我成功。但如果它反复失败 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


}

标签: javascriptasync-awaites6-promise

解决方案


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

setTimeout如果你想在通话之间有一些延迟,你可以打电话给 retry


推荐阅读