javascript / expert
Snippet
Optimizing Server Component Data Fetching with Parallel Promises
In Next.js Server Components, sequentially awaiting multiple async calls creates a 'waterfall' where each request must finish before the next starts. By initiating promises simultaneously and awaiting them with Promise.all, we significantly reduce the total load time.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import { getPosts, getCategories } from '@/lib/api';export default async function Dashboard() {// Fetching data in parallel to avoid waterfallsconst postsPromise = getPosts();const categoriesPromise = getCategories();const [posts, categories] = await Promise.all([postsPromise, categoriesPromise]);return (<div><PostList items={posts} /><CategorySidebar items={categories} /></div>);}
nextjs
Breakdown
1
const postsPromise = getPosts();
Initiates the fetch operation immediately without blocking execution.
2
await Promise.all([...])
Waits for all promises to resolve concurrently, maximizing throughput.