Two Fetches at Once
Part of the Next.js Essentials section of Coddy's React journey — lesson 25 of 47.
A page usually needs more than one thing. The obvious way to write it is also the slow way:
const dishes = await getDishes(); // 60ms
const drinks = await getDrinks(); // 60ms, starting only now
// total: 120msawait means stop here. The second load doesn't even begin until the first one has finished, even though it never needed the first one's result.
Start them both, then wait for both:
const [dishes, drinks] = await Promise.all([
getDishes(),
getDrinks(),
]);
// total: 60msThe trick is in the timing. Calling getDishes() without await starts the work and hands back a promise immediately, so by the time Promise.all begins waiting, both loads are already running. It resolves to an array of results, in the order you listed them.
The rule of thumb:
- One load needs the other's result → sequential
awaits, no way around it - They're independent →
Promise.all
Two loads is a small win. Five is the difference between a page that feels instant and one that doesn't.
Challenge
Easyapp/page.jsx loads dishes and drinks one after the other. They have nothing to do with each other, so run them together.
- Replace the two sequential
awaits with a singleawait Promise.all([...]), destructured intodishesanddrinks.
lib/data.js is locked, and it watches whether the two loads ever overlapped. #report must end up reading Ran together instead of Ran one at a time.
Try it yourself
import './globals.css';
export const metadata = {
title: 'My App',
};
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
{children}
</body>
</html>
);
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Next.js Essentials
2Routing & Links
Folders Are RoutesNested RoutesLinking PagesDynamic RoutesNot Found PagesRecap: Routing5Data on the Server
Async ComponentsAwaiting Route ParamsTwo Fetches at OnceLoading StatesHandling ErrorsRecap: Data Fetching