重试Javascript.Promise。拒绝次数有限或直到成功 [英] Retry on Javascript.Promise.reject a limited number of times or until success

查看:177
本文介绍了重试Javascript.Promise。拒绝次数有限或直到成功的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从客户端调用的函数 myMainFunction ,依次调用 mypromisified 函数。 / p>

场景:
mypromisified 函数可能会间歇性失败,我需要调用



我到目前为止所拥有的 p>

以下代码说明了我的情况,并重复执行直到成功为止,但它会无限期地尝试,直到达到特定计数为止



  //从clientmyMainFuntion()调用一次;函数rejectDelay(delay,reason){//调用main以延迟的时间间隔运行,直到成功// //但只想在有限的时间内调用它setTimeout(()=> {myMainFuntion(); //在此处再次调用main函数,但要有一个延迟},delay);} function myMainFuntion(){var delay = 100; var trys = 3; tryAsync()。catch(rejectDelay.bind(null,delay));} function tryAsync(){return new Promise(function(resolve,reject){{var rand = Math.random(); console.log(rand); if (rand< 0.8){reject(rand);} else {resolve();}});}  



rejectDelay 内的循环当然不会像计数器那样工作即使在setInterval内部的实际函数执行之前就增加了,所以不确定如何执行此操作?所以...



我尝试了 promisifying setInterval 像这样的事情知道它会失败:(因为它不会减少计数器,但是也不知道如何正确处理它。



  function rejectDelay(delay,maximumTries,reason){返回新的Promise(function(resolve,拒绝){console.log(tries +'剩余的');如果(--maximumTries> 0){setTimeout(function(){foo();},500);}});} function myMainFunction(){var delay = 100; var maximumTries = 3; tryAsync()。catch(rejectDelay.bind(null, delay,maximumTries));}  

解决方案

使用很多我经常使用的辅助函数,这变得非常简单



辅助函数

  Promise.wait =(时间)=>新的Promise(resolve => setTimeout(resolve,time || 0)); 
Promise.retry =(cont,fn,delay)=> fn()。catch(err => cont> 0?Promise.wait(delay).then(()=> Promise.retry(cont-1,fn,delay)):Promise.reject('失败' ));

代码:

  function myMainFuntion(){
var delay = 100;
var trys = 3;
Promise.retry(tries,tryAsync,delay);
}




辅助程序的ES5版本




  Promise.wait = function(time){
return new Promise(function(resolve){
return setTimeout(resolve,time || 0);
});
};
Promise.retry =函数(cont,fn,延迟){
返回fn()。catch(function(err){
return cont> 0?Promise.wait(delay)。 then(function(){
return Promise.retry(cont-1,fn,delay);
}):Promise.reject('failed');
});
};


I have a function say myMainFunction that is called from a client, that in turn calls mypromisified function.

Scenario: mypromisified function can fail intermittently and I need to call this function with a delay (at an exponential increase) until success or until max no of tries reached.

What I have so far

The following code illustrates my scenario and repeats itself until success, but it tries indefinitely and not until certain count is reached

// called once from the client
myMainFuntion();

function rejectDelay(delay, reason) {
   // call main function at a delayed interval until success 
   // but would want to call this only a limited no of times
    setTimeout(() => {
      myMainFuntion(); // calling main function again here but with a delay
    }, delay);
}


function myMainFuntion() {
  var delay = 100;
  var tries = 3;
  tryAsync().catch(rejectDelay.bind(null, delay));
}

function tryAsync() {
  return new Promise(function(resolve, reject) {
    var rand = Math.random();
    console.log(rand);
    if (rand < 0.8) {
      reject(rand);
    } else {
      resolve();
    }
  });

}

while loop inside the rejectDelay would certainly not work as the counter would increment even before the actual function inside setInterval is executed, so am unsure as to how to go about this? so...

I tried promisifying the setInterval something like this knowing it will fail :( as it doesnt decrement the counter, but not sure how to get it right either .

function rejectDelay(delay, maximumTries, reason) {
  return new Promise(function (resolve, reject) {
    console.log(tries + ' remaining');
    if (--maximumTries > 0) {
      setTimeout(function() {
        foo();
      }, 500);
    } 
  });
}
function myMainFunction() {
  var delay = 100;
  var maximumTries = 3;
  tryAsync().catch(rejectDelay.bind(null, delay, maximumTries));
}

解决方案

Using a couple of helper functions I've used a lot, this becomes very easy

The "helpers"

Promise.wait = (time) => new Promise(resolve => setTimeout(resolve, time || 0));
Promise.retry = (cont, fn, delay) => fn().catch(err => cont > 0 ? Promise.wait(delay).then(() => Promise.retry(cont - 1, fn, delay)) : Promise.reject('failed'));

The code:

function myMainFuntion() {
      var delay = 100;
      var tries = 3;
      Promise.retry(tries, tryAsync, delay);
}

ES5 versions of the helpers

Promise.wait = function (time) {
    return new Promise(function (resolve) {
        return setTimeout(resolve, time || 0);
    });
};
Promise.retry = function (cont, fn, delay) {
    return fn().catch(function (err) {
        return cont > 0 ? Promise.wait(delay).then(function () {
            return Promise.retry(cont - 1, fn, delay);
        }) : Promise.reject('failed');
    });
};

这篇关于重试Javascript.Promise。拒绝次数有限或直到成功的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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