-
Notifications
You must be signed in to change notification settings - Fork 0
/
serialParallel.js
51 lines (43 loc) · 1.26 KB
/
serialParallel.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
function fakeAPICall(id, delay) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (typeof id === 'number') {
resolve(`Response from API call ${id}`);
} else {
reject(`Provide id number in API call}`);
}
}, delay);
});
}
async function serialExecution() {
console.time('serialExecution')
try {
const response1 = await fakeAPICall(1, 1000);
console.log(response1);
const response2 = await fakeAPICall(2, 1500);
console.log(response2);
const response3 = await fakeAPICall(3, 1200);
console.log(response3);
} catch (error) {
console.error(error);
}
console.timeEnd('serialExecution')
}
async function parallelExecution() {
console.time('parallelExecution')
try {
const promises = [
fakeAPICall(1, 1000),
fakeAPICall(2, 1500),
fakeAPICall(3, 1200)
];
const responses = await Promise.all(promises);
// const responses = await Promise.allSettled(promises);
console.log(responses);
} catch (error) {
console.error(error);
}
console.timeEnd('parallelExecution')
}
serialExecution();
parallelExecution();