-
Notifications
You must be signed in to change notification settings - Fork 0
/
queue.js
65 lines (54 loc) · 1.31 KB
/
queue.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
function createScheduler(fetchFn, options) {
const queue = [];
let isPaused = false;
let running = false;
let concurrency = options.concurrency || Infinity;
// true: valid
// false: abort // todo ?
// number: retry after the given time
let validateResponse = options.validateResponse || (() => true);
function next() {
running = true;
if (queue.length === 0) {
running = false;
return;
}
if (isPaused || concurrency <= 0) {
return;
}
concurrency--;
const { request, resolve } = queue.shift();
const cb = r => {
const responseValid = validateResponse(r);
if (typeof responseValid === "number") {
isPaused = true;
queue.push({ request, resolve });
return setTimeout(
() => {
isPaused = false;
concurrency++;
next();
},
responseValid
);
}
resolve(r);
concurrency++;
next();
};
request().then(cb, cb);
next();
}
return function(...args) {
let resolver = () => {};
const promise = new Promise(resolve => {
resolver = resolve;
});
queue.push({ request: () => fetchFn(...args), resolve: resolver });
if (!running) {
next();
}
return promise;
};
}
module.exports = createScheduler;