如何反复调用异步方法,直到在本机JavaScript中获得成功? [英] How to call a async method repeatedly until you get success in native JavaScript?

查看:45
本文介绍了如何反复调用异步方法,直到在本机JavaScript中获得成功?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个异步方法,该方法返回成功或失败.我必须不断从另一个方法调用此异步方法,直到获得成功.但是,如果它连续5次失败,那么我必须停止调用它.

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


}

推荐答案

重试应该很容易,只需进行一点递归即可.基本上,如果请求成功,则返回.如果失败,则捕获该错误,然后再尝试少1次尝试.

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

这篇关于如何反复调用异步方法,直到在本机JavaScript中获得成功?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆