-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
66 lines (60 loc) · 1.86 KB
/
index.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
65
66
'use strict';
const events = require("events");
const util = require('util');
const debug = util.debuglog('simple-retry');
class SimpleRetry {
constructor(option) {
option = option || {};
if (!isFuction(option.fn)) {
throw new Error('please provide retry function.');
}
this.fn = option.fn;
this.retry_delay = 150;
this.current_delay = this.retry_delay;
this.retry_backoff = option.factor || 1.7;
this.attempts = 0;
this.isReady = false;
this.max_attempts = option.max_attempts;
this.max_delay = option.max_delay;
this.retry_timer = null;
}
retry() {
let self = this;
self.attempts++;
debug(`retry for ${self.attempts} attemps.`);
self.fn((error, result) => {
if (self.retry_timer) {
return;
}
if (error) {
self.emit('error', error);
self.current_delay = Math.floor(self.current_delay * self.retry_backoff);
self.isReady = false;
if (self.max_delay && self.current_delay > self.max_delay) {
self.current_delay = self.max_delay;
}
if (self.max_attempts && self.attempts >= self.max_attempts) {
debug(`retry max ${self.attempts} attemps.`);
self.current_delay = self.retry_delay;
self.attempts = 0;
self.emit('finish', 'retry max');
} else {
debug(`retry in ${self.current_delay}ms.`);
self.retry_timer = setTimeout(() => {
self.retry_timer = null;
self.retry();
}, self.current_delay);
}
} else {
self.current_delay = self.retry_delay;
self.retry_timer = null;
self.attempts = 0;
self.isReady = true;
self.emit('finish', result);
}
})
}
}
util.inherits(SimpleRetry, events.EventEmitter);
let isFuction = (fn) => typeof fn == 'function' || false;
module.exports = SimpleRetry;