-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
63 lines (49 loc) · 1.42 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
"use strict";
function promiseSupported(Promise){
return typeof Promise !== "undefined";
}
module.exports = function(_Promise) {
_Promise = _Promise || Promise;
if (!promiseSupported((_Promise))) {
throw new Error('Promise not supported');
}
if (_Promise && typeof _Promise.all === "function" && typeof _Promise.race === "function"){
return arguments[0].series = series;
} else {
return series.apply(this, arguments);
}
};
function series (promises, concurrent) {
var results = null;
promises = promises.slice();
concurrent = concurrent || 1;
return new Promise(function (resolve, reject) {
function next(result) {
var concurrentPromises = [];
var promise;
if (!results) {
results = [];
} else {
results = results.concat(result);
}
if (promises.length) {
while (concurrentPromises.length < concurrent && promises.length) {
var promise = promises.shift();
if (typeof promise === 'function') {
promise = promise();
}
if (!promise || typeof promise.then !== 'function') {
promise = Promise.resolve();
}
concurrentPromises.push(promise);
}
Promise.all(concurrentPromises)
.then(next)
.catch(reject);
} else {
resolve(results);
}
}
next();
});
}