Performance: Parallel data fetching pattern
This pattern affects page load speed by reducing the time to fetch multiple data sources simultaneously, improving the Largest Contentful Paint (LCP).
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 | 0 | High due to delayed content | [X] Bad |
| Parallel fetches with Promise.all | Minimal | 0 | Low due to faster content availability | [OK] Good |
Parallel data fetching pattern in Next.js?Promise.all?await Promise.all([fetch(url1), fetch(url2)]) runs both fetches at the same time and waits for both results.async function fetchData() {
const [res1, res2] = await Promise.all([
fetch('https://api.example.com/data1'),
fetch('https://api.example.com/data2')
]);
console.log(res1.ok, res2.ok);
}
fetchData();res1.ok and res2.ok will be true, so console logs [true, true].async function getData() {
const data1 = fetch('/api/data1');
const data2 = fetch('/api/data2');
const results = await Promise.all(data1, data2);
return results;
}Promise.all([data1, data2]) to run fetches in parallel correctly.Pass the test and this pattern moves unknown