-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathindex.js
More file actions
executable file
·94 lines (84 loc) · 2.34 KB
/
index.js
File metadata and controls
executable file
·94 lines (84 loc) · 2.34 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
'use strict';
const EventEmitter = require('events');
/**
* Produces an object that represents a stream of events generated by polling a provided function.
* @param {object} options The to configure Pollify with.
* @param {number} options.rate The rate with which to execute pollFn. Is in milliseconds.
* @param {string} options.mode The mode of the pollFn return type. Possible values are 'promise', 'callback',
* and 'return'
* @param {function} pollFn The function to be polled. The results of pollFn() will be emitted. Must be a Promise
* @param {*} fnArgs The arguments pollFn should be called with.
*/
function Pollify (options, pollFn, ...fnArgs) {
const emitter = Object.create(new EventEmitter());
options.rate = options.rate || 0;
let stopped = false;
let firstRun = true;
const pollTypes = {
_promise (startTime) {
const req = pollFn(...fnArgs).then(data => {
emit('data', data, startTime);
}).catch(e => emit('error', e));
// eslint-disable-next-line promise/catch-or-return
req.then(() => repoll(startTime));
},
_callback (startTime) {
pollFn(...fnArgs, (e, ...data) => {
if (e) {
return emit('error', e);
}
emit('data', ...data, startTime);
repoll(startTime);
});
},
_return (startTime) {
try {
const data = pollFn(...fnArgs);
emit('data', data, startTime);
} catch (e) {
emit('error', e);
}
repoll(startTime);
}
};
function emit (...args) {
if (firstRun) {
return process.nextTick(() => emitter.emit(...args));
}
return emitter.emit(...args);
}
function poll () {
if (stopped) {
return;
}
const startTime = Date.now();
pollTypes['_' + options.mode](startTime);
firstRun = false;
}
function repoll (startTime) {
const timeDiff = options.rate - (Date.now() - startTime);
if (timeDiff > 0) {
return setTimeout(poll, timeDiff);
}
return setImmediate(poll);
}
poll();
return Object.assign(emitter, {
/**
* Will start the event stream. Polls are started by default on construction.
*/
start () {
if (stopped) {
stopped = false;
poll();
}
},
/**
* Will stop the event stream.
*/
stop () {
stopped = true;
}
});
}
module.exports = Pollify;