Performance: Parallel data fetching
This affects page load speed by reducing the time waiting for multiple data sources to respond, improving the Largest Contentful Paint (LCP).
Jump into concepts and practice - no test required
const [data1, data2, data3] = await Promise.all([ fetch('/api/data1').then(res => res.json()), fetch('/api/data2').then(res => res.json()), fetch('/api/data3').then(res => res.json()) ]);
const data1 = await fetch('/api/data1').then(res => res.json()); const data2 = await fetch('/api/data2').then(res => res.json()); const data3 = await fetch('/api/data3').then(res => res.json());
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Sequential fetches | Minimal | 1 (after all data) | High (delayed paint) | [X] Bad |
| Parallel fetches with Promise.all | Minimal | 1 (after all data) | Low (faster paint) | [OK] Good |
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