返回 AiToEarn
async-dependencies.md
1 ---
2 title: Dependency-Based Parallelization
3 impact: CRITICAL
4 impactDescription: 2-10× improvement
5 tags: async, parallelization, dependencies, better-all
6 ---
7
8 ## Dependency-Based Parallelization
9
10 For operations with partial dependencies, use `better-all` to maximize parallelism. It automatically starts each task at the earliest possible moment.
11
12 **Incorrect (profile waits for config unnecessarily):**
13
14 ```typescript
15 const [user, config] = await Promise.all([
16 fetchUser(),
17 fetchConfig()
18 ])
19 const profile = await fetchProfile(user.id)
20 ```
21
22 **Correct (config and profile run in parallel):**
23
24 ```typescript
25 import { all } from 'better-all'
26
27 const { user, config, profile } = await all({
28 async user() { return fetchUser() },
29 async config() { return fetchConfig() },
30 async profile() {
31 return fetchProfile((await this.$.user).id)
32 }
33 })
34 ```
35
36 **Alternative without extra dependencies:**
37
38 We can also create all the promises first, and do `Promise.all()` at the end.
39
40 ```typescript
41 const userPromise = fetchUser()
42 const profilePromise = userPromise.then(user => fetchProfile(user.id))
43
44 const [user, config, profile] = await Promise.all([
45 userPromise,
46 fetchConfig(),
47 profilePromise
48 ])
49 ```
50
51 Reference: [https://github.com/shuding/better-all](https://github.com/shuding/better-all)
52
52 lines MARKDOWN