Next.js
/Intermediate
Parallel Data Fetching
Definition
Initiating multiple asynchronous data requests at the exact same time, rather than waiting for one to finish before starting the next.
Explain Like I'm New
If you need to fetch 'User Profile' (takes 2 seconds) and 'Recent Posts' (takes 2 seconds). If you fetch them sequentially, the page takes 4 seconds to load. If you fetch them in parallel, the page takes 2 seconds to load.
Real World Example
A dashboard that shows 4 different charts. You fire off all 4 database queries simultaneously so the user doesn't have to wait for them to load one-by-one.
Common Use Cases
- •Complex dashboards
- •Aggregating multiple data sources
Interactive Example
export default async function Dashboard() { // ❌ BAD: Sequential Fetching (Waterfalls) // Takes 4 seconds total! // const user = await fetchUser(); // const posts = await fetchPosts(); // ✅ GOOD: Parallel Fetching // 1. Initiate the requests simultaneously (Do NOT use 'await' here) const userPromise = fetchUser(); const postsPromise = fetchPosts(); // 2. Await them all at once! Takes only 2 seconds total! const [user, posts] = await Promise.all([userPromise, postsPromise]); return ( <div> <h1>{user.name}</h1> <p>Total Posts: {posts.length}</p> </div> ); }
Interview Questions
basic
- What standard JavaScript method is used to await multiple promises at the same time?
intermediate
- In parallel fetching, what happens if one of the three promises fails/rejects?