Next.js Fetching in Parallel
Two fetches can run at the same time. Promise.all starts both, then waits for both.
Two waits, one after the other
The page waits for the books, then waits for the count. The waits add up to about 1,600 ms.
export default async function SequentialPage() {
const books = await getBooksSlow(800);
const readCount = await getReadCount();
return (
<main>
<h1>Sequential fetch</h1>
<p>Loaded {books.length} books and {readCount} read</p>
</main>
);
}Two waits, at the same time
Promise.all starts both waits together. The page takes about 800 ms, one wait long.
export default async function ParallelPage() {
const [books, readCount] = await Promise.all([
getBooksSlow(800),
getReadCount(),
]);
return (
<main>
<h1>Parallel fetch</h1>
<p>Loaded {books.length} books and {readCount} read</p>
</main>
);
}Example
curl -s -o /dev/null -w "parallel: %{time_total}s\n" http://localhost:3113/parallel
curl -s -o /dev/null -w "sequential: %{time_total}s\n" http://localhost:3113/sequentialKey points
- Parallel: two jobs running at the same time, not one after the other
- Promise.all: the call that starts several promises and waits for all of them
- Two 800 ms fetches in parallel take about 800 ms. One after the other takes about 1,600 ms.
- Sequential means one wait, then the next wait. The times add up.
- The page shows the same line either way: 5 books and 2 read.
In this example, the checks time both pages on the dev server. The parallel page answers in 0.85 seconds, about one 800 ms wait. The sequential page answers in 1.63 seconds, about two waits added together. Both pages show the same line, Loaded 5 books and 2 read. The only difference is the waiting. The first visit to each page is slower, because the dev server compiles the page first.
Note
Start the slow fetches together when neither one needs the other result.
Try it Yourself
Edit the code, then press Run.
Running is simulated · TypeScript Playground
Exercise
How long do two 800 ms fetches take in parallel?