52 lines
1.3 KiB
Markdown
52 lines
1.3 KiB
Markdown
---
|
||
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)
|