fb79a15508
- 添加 sections 定义文件,包含性能优化各领域分类 - 添加规则模板文件,规范文档结构和标签定义 - 添加异步操作优化规则,包括防止瀑布流、并行化、延迟等待等 - 添加包大小优化规则,包括避免桶式导入、动态导入、预加载等 - 添加服务端性能优化规则,包括 API 路
39 lines
1.1 KiB
Markdown
39 lines
1.1 KiB
Markdown
---
|
||
title: Prevent Waterfall Chains in API Routes
|
||
impact: CRITICAL
|
||
impactDescription: 2-10× improvement
|
||
tags: api-routes, server-actions, waterfalls, parallelization
|
||
---
|
||
|
||
## Prevent Waterfall Chains in API Routes
|
||
|
||
In API routes and Server Actions, start independent operations immediately, even if you don't await them yet.
|
||
|
||
**Incorrect (config waits for auth, data waits for both):**
|
||
|
||
```typescript
|
||
export async function GET(request: Request) {
|
||
const session = await auth()
|
||
const config = await fetchConfig()
|
||
const data = await fetchData(session.user.id)
|
||
return Response.json({ data, config })
|
||
}
|
||
```
|
||
|
||
**Correct (auth and config start immediately):**
|
||
|
||
```typescript
|
||
export async function GET(request: Request) {
|
||
const sessionPromise = auth()
|
||
const configPromise = fetchConfig()
|
||
const session = await sessionPromise
|
||
const [config, data] = await Promise.all([
|
||
configPromise,
|
||
fetchData(session.user.id)
|
||
])
|
||
return Response.json({ data, config })
|
||
}
|
||
```
|
||
|
||
For operations with more complex dependency chains, use `better-all` to automatically maximize parallelism (see Dependency-Based Parallelization).
|