Files
2026-07-13 21:36:17 +08:00

38 lines
1.1 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
title: 防止 API 路由中的瀑布链
impact: CRITICAL
impactDescription: 210 倍性能提升
tags: api-routes, server-actions, waterfalls, parallelization
---
## 防止 API 路由中的瀑布链
在 API 路由和 Server Actions 中,应**立即**启动独立的操作,即使你还不需要 `await` 它们。
**错误写法(config 等待 authdata 同时等待两者):**
```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 })
}
```
**正确写法(auth 和 config 立即启动):**
```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 })
}
对于依赖链更复杂的操作,请使用 `better-all` 来自动最大化并行度(参见「基于依赖的并行化」)。