Skip to content

Commit

Permalink
add: concurrency batches samples
Browse files Browse the repository at this point in the history
  • Loading branch information
thutasann committed Feb 25, 2025
1 parent 4ef25c1 commit f41502b
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
24 changes: 24 additions & 0 deletions data_structures/js_questions/concurrency/batch_fetch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
async function fetchUsersBatch(batch: number[]): Promise<string[]> {
return new Promise<string[]>((resolve) => {
setTimeout(() => {
resolve(batch.map((id) => `User ${id}`));
}, 2000);
});
}

async function batchFetchUsers(totalUsers: number, batchSize: number) {
const message = 'Batch Fetching Time';
console.time(message);

const userIds = Array.from({ length: totalUsers }, (_, i) => i + 1);
const batches: number[][] = [];

for (let i = 0; i < userIds.length; i++) {
batches.push(userIds.slice(i, i + batchSize));
}

const allResults = await Promise.all(batches.map((batch) => fetchUsersBatch(batch)));
console.log(allResults.flat());
console.timeEnd(message);
}
batchFetchUsers(10, 2);
39 changes: 39 additions & 0 deletions data_structures/js_questions/concurrency/why_use_promise_all.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
async function fetchUsers() {
return new Promise<string>((resolve) => setTimeout(() => resolve('User Data'), 2000));
}

async function fetchPosts() {
return new Promise<string>((resolve) => setTimeout(() => resolve('Product Data'), 3000));
}

/**
* Sequential Time: 5005.678ms
* Total Time: 5 seconds (because each await waits for the previous one to finish).
*/
async function fetchDataSequentital() {
const message = 'Sequential time';
console.time(message);

const users = await fetchUsers();
const posts = await fetchPosts();

console.log({ users, posts });
console.timeEnd(message);
}

/**
* Parallel Time: 3002.456ms
* - Total Time: 3 seconds (instead of 5s)!
* - ✅ Use Promise.all() whenever tasks are independent and can run in parallel.
* - ✅ It makes execution faster than multiple sequential await calls! 🚀
*/
async function fetchDataParallel() {
const message = 'Parallel Time';
console.time(message);

const [user, posts] = await Promise.all([fetchUsers(), fetchPosts()]);

console.log({ user, posts });
console.timeEnd(message);
}
fetchDataParallel();

0 comments on commit f41502b

Please sign in to comment.