项目文件夹

文件
2026-07-13 21:36:17 +08:00

52 行
1.3 KiB
Markdown

此文件含有模棱两可的 Unicode 字符
此文件含有可能会与其他字符混淆的 Unicode 字符。 如果您是想特意这样的,可以安全地忽略该警告。 使用 Escape 按钮显示他们。
---
title: Dependency-Based Parallelization
impact: CRITICAL
impactDescription: 2-10× improvement
tags: async, parallelization, dependencies, better-all
---
## 基于依赖关系的并行化
对于存在部分依赖关系的操作,使用 `better-all` 来最大化并行度。它会自动让每个任务在最早可行的时刻启动。
**错误做法(profile 不必要地等待 config):**
```typescript
const [user, config] = await Promise.all([
fetchUser(),
fetchConfig()
])
const profile = await fetchProfile(user.id)
```
**正确做法(config 和 profile 并行运行):**
```typescript
import { all } from 'better-all'
const { user, config, profile } = await all({
async user() { return fetchUser() },
async config() { return fetchConfig() },
async profile() {
return fetchProfile((await this.$.user).id)
}
})
```
**无需额外依赖的替代方案:**
我们也可以先创建所有 Promise,最后再统一执行 `Promise.all()`
```typescript
const userPromise = fetchUser()
const profilePromise = userPromise.then(user => fetchProfile(user.id))
const [user, config, profile] = await Promise.all([
userPromise,
fetchConfig(),
profilePromise
])
```
参考链接:[https://github.com/shuding/better-all](https://github.com/shuding/better-all)