-
-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathasync sequentializer
More file actions
29 lines (25 loc) · 838 Bytes
/
async sequentializer
File metadata and controls
29 lines (25 loc) · 838 Bytes
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
const asyncSequentializer = (() => {
const toPromise = (x) => {
if(x instanceof Promise) { // if promise just return it
return x;
}
if(typeof x === 'function') {
// if function is not async this will turn its result into a promise
// if it is async this will await for the result
return (async () => await x())();
}
return Promise.resolve(x)
}
return (list) => {
const results = [];
return list
.reduce((lastPromise, currentPromise) => {
return lastPromise.then(res => {
results.push(res); // collect the results
return toPromise(currentPromise);
});
}, toPromise(list.shift()))
// collect the final result and return the array of results as resolved promise
.then(res => [...results, res]);
}
})();