Skip to content

Instantly share code, notes, and snippets.

@alaindet
Last active November 14, 2021 20:50
Show Gist options
  • Save alaindet/d0653e4cbc9ee3b52df880c6dba1970e to your computer and use it in GitHub Desktop.
Save alaindet/d0653e4cbc9ee3b52df880c6dba1970e to your computer and use it in GitHub Desktop.
JavaScript serial and parallel execution
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