-
Notifications
You must be signed in to change notification settings - Fork 0
/
exponentialBackOff.js
65 lines (59 loc) · 1.88 KB
/
exponentialBackOff.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// A function that keeps trying, "toTry" until it returns expected value or has
// tried "max" number of times. First retry has a delay of "delay".
// "callback" is called upon success.
function exponentialBackoff(toTry, params, max, delay, cb) {
var result = toTry(params);
// console.log('max',max,'next delay',delay);
if (result.response && result.response.length) {
if (!params.response) {
params.response = [];
}
var t = result.response.concat(params.response);
params.response = t;
result.response = t;
}
if (result && Number(result.unprocessedKeys) === 0) {
console.log('result', result);
cb(result);
} else {
if (max > 0) {
params.requestedItems = Number(result.unprocessedKeys);
setTimeout(function() {
exponentialBackoff(toTry, params, --max, delay * 2, cb);
}, delay);
} else {
console.log('we give up');
return null;
}
}
}
/*
* This function represent a sample DynamoDB API.
* Return random result either completed result or partial result.
* If partial result returned, try to call exponentially query until completed result return
* or max attemp time hit.
*
* params => query param that's sent to DynamoDB
* More info about params and return values is here http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#batchGetItem-property
*/
function num(params) {
var res = {};
var response = [];
for (var i = params.requestedItems; i > 0 ; i--) {
var randomboolen = Math.random() > 0.4;
if (randomboolen) {
response.push(i);
}
}
res.response = response;
res.unprocessedKeys = params.requestedItems - response.length;
return res;
}
var params = {
requestedItems: 20,
// result: [],
// unprocessedKeys: 0
}
exponentialBackoff(num, params, 4, 100, function(re) {
console.log(re);
})