-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathPromises.js
95 lines (83 loc) · 2.42 KB
/
Promises.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
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
95
// Copyright (c) 2015, Evan Summers (twitter.com/evanxsummers)
// ISC license, see http://github.com/evanx/redexutil/LICENSE
const logger = Loggers.create(__filename, 'info');
function createCallback(resolve, reject) {
return (err, reply) => {
if (err) {
reject(err);
} else {
resolve(reply);
}
};
}
class Promises {
create(fn) {
return new Promise((resolve, reject) => fn(createCallback(resolve, reject)));
}
delay(millis) {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(), millis);
});
}
timeout(reason, timeout, promise) {
if (timeout) {
return new Promise((resolve, reject) => {
logger.warn('timeout', typeof promise);
promise.then(resolve, reject);
setTimeout(() => {
reject(reason + ' (' + timeout + 'ms)');
}, timeout);
});
} else {
return promise;
}
}
map(values, fn) {
return Promise.all(values.map(fn));
}
staggered(maxDelay, totalPeriod, values, fn) {
if (lodash.isEmpty(values)) {
return Promise.resolve([]);
}
let delay = Math.floor(totalPeriod/values.length);
logger.debug('staggered', maxDelay, delay, values.length);
return Promise.all(values.map(async (value, index) => {
await this.delay(Math.min(maxDelay, delay));
return fn(value);
}));
}
series(values, fn) {
if (lodash.isEmpty(values)) {
return Promise.resolve([]);
}
values = values.slice(0);
return new Promise((resolve, reject) => {
let results = [];
function next(result) {
logger.debug('series next', result, results.length, values.length);
results.push(result);
if (lodash.isEmpty(values)) {
resolve(results);
}
fn(values.shift()).then(next, reject);
}
logger.debug('series start', values.length);
return fn(values.shift()).then(next, reject);
});
}
notEmpty(value, reason) {
if (!lodash.isEmpty(value)) {
return Promise.resolve(value);
} else {
return Promise.reject(reason);
}
}
isEmpty(value, reason) {
if (lodash.isEmpty(value)) {
return Promise.resolve(value);
} else {
return Promise.reject(reason);
}
}
};
module.exports = new Promises();