-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathajscript.js
50 lines (40 loc) · 1.15 KB
/
ajscript.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
"use strict";
// do something like `throw new Error('break');` to stop
Promise._forEach = async function (arr, fn) {
await arr.reduce(async function (promise, el, i) {
await promise;
await fn(el, i, arr);
}, Promise.resolve());
};
Promise._parallel = async function (limit, arr, fn) {
let index = 0;
let actives = [];
let results = [];
function launch() {
let _index = index;
let p = fn(arr[_index], _index, arr);
// some tasks may be synchronous
// so we must push before removing
actives.push(p);
p.then(function _resolve(result) {
let i = actives.indexOf(p);
actives.splice(i, 1);
results[_index] = result;
});
index += 1;
}
// start tasks in parallel, up to limit
for (; actives.length < limit; ) {
launch();
}
// keep the task queue full
for (; index < arr.length; ) {
// wait for one task to complete
await Promise.race(actives);
// add one task again
launch();
}
// wait for all remaining tasks
await Promise.all(actives);
return results;
};