Last active
November 14, 2021 20:50
-
-
Save alaindet/d0653e4cbc9ee3b52df880c6dba1970e to your computer and use it in GitHub Desktop.
JavaScript serial and parallel execution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const delay = 1000; | |
const iterations = 3; | |
const fakeRequest = () => new Promise((resolve, reject) => { | |
setTimeout(() => resolve(11), delay); | |
}); | |
// Sync | |
(async () => { | |
console.time('sync'); | |
const result = []; | |
for (let i = 0; i < iterations; i++) { | |
const data = await fakeRequest(); | |
result.push(data); | |
} | |
console.timeEnd('sync'); | |
})(); | |
// Async | |
(async () => { | |
console.time('async'); | |
const result = []; | |
const requests = []; | |
for (let i = 0; i < iterations; i++) { | |
const request = fakeRequest().then(data => result.push(data)); | |
requests.push(request); | |
} | |
await Promise.all(requests); | |
console.timeEnd('async'); | |
})(); | |
// async: 1.002s | |
// sync: 3.006s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment