javascript / intermediate
Snippet
Parallel Data Fetching in Server Components
By initiating multiple fetch requests without 'await' and then using Promise.all, you avoid 'waterfalls' where requests happen sequentially. This significantly reduces the total loading time of a Next.js page.
snippet.js
1
2
3
4
5
6
7
8
export default async function Page({ params }) {const userData = getUser(params.id);const postsData = getPosts(params.id);const [user, posts] = await Promise.all([userData, postsData]);return <div>{user.name} has {posts.length} posts</div>;}
nextjs
Breakdown
1
const userData = getUser(params.id)
Starts the promise immediately without blocking the next line.
2
await Promise.all([userData, postsData])
Waits for all initiated requests to complete concurrently.