読み方のヒント
矢印ボタン(または ← → キー)でページを移動できます。
商品・在庫・おすすめ商品を、順に読んでみます。
export default async function ProductPage({ params }: PageProps<"/products/[id]">) {
const { id } = await params;
const product = await getProduct(id);
if (product === undefined) notFound();
const stock = await getStock(id);
const related = await getRelatedProducts(product.category);
// ...
}
getStock と getRelatedProducts は、どちらも product があれば始められ、お互いを待つ必要がありません。それなのに、上の書き方では、在庫を読み終えてから、おすすめ商品を読み始めます。
const [stock, related] = await Promise.all([
getStock(id),
getRelatedProducts(product.category),
]);
Promise.all は、いくつかの Promise を同時に始め、すべてが終わるのを待ちます。
| 書き方 | かかる時間(在庫 300ms、おすすめ 200ms のとき) |
|---|---|
順に await | 約 500ms |
Promise.all | 約 300ms |
3 / 17