It would be nice if the delay parameter in ReattemptOptions was something like:
delay?: number | ((value: any, attempt: number) => number);
And in the reattemptAsync and reattempt we could check:
function tryDelayAsync(duration: number) {
setTimeout(() => {
currentAttempts--;
reattemptAsync(fn(), fn, resolve, reject);
}, duration);
}
if (isFunction(delay)) {
const delayDuration = delay(error, currentAttempts - 1);
if (delayDuration >= 0) {
tryDelayAsync(delayDuration);
} else {
tryDelayAsync(defaultDelay); // defaultDelay = 0
}
} else {
tryDelayAsync(delay);
}
That way for example:
function delayFn(value: any, index: number): number {
return 1000;
}
const promise = Reattempt.run({ times: 2, delay: delayFn }, fn);
The only thing that is somewhat ugly is the index parameters is decreasing over time instead of increasing. Ideally we want to pass an increasing sequence so for example we can calculate a exponental backoff like:
function delayFn(value: any, index: number): number {
let delay = Math.pow(2, index); // factor is 2
const min = 0; // Min delay is 0
const max = Math.floor(delay);
delay = Math.floor(Math.random() * (max - min + 1)) + min;
return Math.round(delay);
}
I have a proof of concept on my local branch.
Thoughts?
It would be nice if the delay parameter in
ReattemptOptionswas something like:delay?: number | ((value: any, attempt: number) => number);And in the
reattemptAsyncandreattemptwe could check:That way for example:
The only thing that is somewhat ugly is the
indexparameters is decreasing over time instead of increasing. Ideally we want to pass an increasing sequence so for example we can calculate a exponental backoff like:I have a proof of concept on my local branch.
Thoughts?