Introduction
Parallel data fetching helps get multiple pieces of data at the same time. This makes your app faster because it does not wait for one request to finish before starting the next.
Jump into concepts and practice - no test required
Parallel data fetching helps get multiple pieces of data at the same time. This makes your app faster because it does not wait for one request to finish before starting the next.
const [data1, data2] = await Promise.all([fetch(url1).then(res => res.json()), fetch(url2).then(res => res.json())]);
Promise.all to run multiple fetch requests at the same time.Promise.all waits for all to finish.const [user, posts] = await Promise.all([ fetch('https://jsonplaceholder.typicode.com/users/1').then(res => res.json()), fetch('https://jsonplaceholder.typicode.com/posts?userId=1').then(res => res.json()) ]);
const [comments, albums] = await Promise.all([ fetch('https://jsonplaceholder.typicode.com/comments?postId=1').then(res => res.json()), fetch('https://jsonplaceholder.typicode.com/albums?userId=1').then(res => res.json()) ]);
This Next.js page fetches user info and their posts at the same time using Promise.all. It then shows the user's name and email, followed by a list of their post titles.
import React from 'react'; export default async function Page() { const [user, posts] = await Promise.all([ fetch('https://jsonplaceholder.typicode.com/users/1').then(res => res.json()), fetch('https://jsonplaceholder.typicode.com/posts?userId=1').then(res => res.json()) ]); return ( <main> <h1>User Info</h1> <p>Name: {user.name}</p> <p>Email: {user.email}</p> <h2>Posts</h2> <ul> {posts.map(post => ( <li key={post.id}>{post.title}</li> ))} </ul> </main> ); }
Always handle errors when fetching data to avoid app crashes.
Parallel fetching is faster but be careful not to overload the server with too many requests.
Parallel data fetching gets multiple data pieces at once to save time.
Use Promise.all with multiple fetch calls for this.
This improves user experience by loading data faster.
Promise.all for data fetching in Next.js?Promise.all behaviorPromise.all runs multiple promises in parallel and waits for all to finish.Promise.all fetches sequentiallyPromise.all in Next.js?Promise.all argument formatPromise.all expects an array of promises, so the fetch calls must be inside an array.Promise.all([fetch(url1), fetch(url2)]). const [res1, res2] = await Promise.all(fetch(url1), fetch(url2)); misses the array brackets.async function fetchData() {
const [userRes, postsRes] = await Promise.all([
fetch('https://api.example.com/user'),
fetch('https://api.example.com/posts')
]);
console.log(userRes.status, postsRes.status);
}
fetchData();fetch returnsfetch returns a Response object with a status property indicating HTTP status.Promise.all resultPromise.all waits for both fetches and returns an array of Response objects. Logging userRes.status and postsRes.status prints their HTTP status codes.async function getData() {
const res1 = fetch('https://api.example.com/data1');
const res2 = fetch('https://api.example.com/data2');
const data1 = await res1.json();
const data2 = await res2.json();
return { data1, data2 };
}res1 and res2res1 and res2 are promises from fetch, not Response objects yet.json() usagejson(). Calling json() directly on a promise causes an error.json() on a promise; you must await the fetch first. -> Option DPromise.all fails fast if any promise rejects, so it can't handle partial success. Promise.allSettled waits for all promises and reports each result, allowing conditional logic.Promise.allSettled, check user info status; if successful, render posts, else skip posts.Promise.allSettled to fetch both, then conditionally render posts if user info succeeded. -> Option C