-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSeriesAsync.js
More file actions
36 lines (28 loc) · 770 Bytes
/
SeriesAsync.js
File metadata and controls
36 lines (28 loc) · 770 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
30
31
32
33
34
35
36
// Given series of async functions and you need to execute sequentially
function a1(callback) {
setTimeout(() => {
console.log("hello Mounika");
callback();
}, 1000);
}
function a2() {
setTimeout(() => {
console.log("hello Sudhakar");
}, 0);
}
// One approach is you need to recursively go and execute functions
const arrayAsync = [a1, a2];
function seriesAsync(currentIndex) {
if (currentIndex < arrayAsync.length) {
arrayAsync[currentIndex](function () {
seriesAsync(currentIndex + 1);
});
}
}
// But usually it will be given in promises only
// so we can use for of with await
for (const promise of arrayAsync) {
await promise;
}
// this will make synchronous as we are using await which will not allow
seriesAsync(0);