Files
skillhub-088-vercel-react-b…/rules/server-parallel-nested-fetching.md
2026-07-13 21:36:17 +08:00

35 lines
1.0 KiB
Markdown

---
title: 并行嵌套数据获取
impact: CRITICAL
impactDescription: 消除服务端瀑布请求
tags: server, rsc, parallel-fetching, promise-chaining
---
## 并行嵌套数据获取
当并行获取嵌套数据时,将依赖的获取操作链式组合到每个条目的 promise 中,这样慢条目就不会阻塞其余条目。
**错误做法(单个慢条目阻塞所有嵌套获取):**
```tsx
const chats = await Promise.all(
chatIds.map(id => getChat(id))
)
const chatAuthors = await Promise.all(
chats.map(chat => getUser(chat.author))
)
```
如果 100 个 `getChat(id)` 中有一个极其缓慢,其余 99 个聊天的作者数据即使已经就绪,也无法开始加载。
**正确做法(每个条目自行链式处理其嵌套获取):**
```tsx
const chatAuthors = await Promise.all(
chatIds.map(id => getChat(id).then(chat => getUser(chat.author)))
)
```
每个条目独立链式处理 `getChat``getUser`,因此一个慢聊天不会阻塞其他条目的作者数据获取。