Awaiting requests one by one
loadAvatars() fetches 50 independent user profiles for a team page. It takes ~10 seconds. Why?
export async function loadAvatars(userIds: string[]): Promise<string[]> { const avatars: string[] = []; for (const id of userIds) { const res = await fetch(`/api/users/${id}`); const user: { avatarUrl: string } = await res.json(); avatars.push(user.avatarUrl); } return avatars;}Show answer
line 4 · Performance trap
Each request waits for the previous one to finish, so total time is the sum of all latencies (50 × ~200ms). The requests are independent and can run concurrently.
export async function loadAvatars(userIds: string[]): Promise<string[]> { return Promise.all( userIds.map(async (id) => { const res = await fetch(`/api/users/${id}`); const user: { avatarUrl: string } = await res.json(); return user.avatarUrl; }), );}Interview follow-up: Strong candidates add that very large lists need a concurrency limit, or a batch endpoint.