【发布时间】:2017-02-24 14:41:09
【问题描述】:
我有一个从客户端调用的函数 myMainFunction,然后又调用 mypromisified 函数。
场景:
mypromisified 函数可能会间歇性失败,我需要延迟调用此函数(以指数增长),直到成功或达到最大尝试次数。
我目前所拥有的
下面的代码说明了我的场景并重复自己直到成功,但它会无限期地尝试,直到达到一定的计数
// 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();
}
});
}
rejectDelay 内的while 循环肯定不会工作,因为即使在 setInterval 中的实际函数执行之前,计数器也会增加,所以不确定如何解决这个问题?所以...
我试过promisifying 和setInterval 这样的东西知道它会失败:( 因为它不会减少计数器,但也不知道如何让它正确。
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));
}
【问题讨论】: