| 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 |
| 16 | const profile = await |
| 17 | ``` |
| 18 | |
| 19 | **Correct (config and profile run in parallel):** |
| 20 | |
| 21 | ```typescript |
| 22 | import { all } |
| 23 | |
| 24 | const { user, |
| 25 | async user() { |
| 26 | return fetchUser(); |
| 27 | }, |
| 28 | async config() { |
| 29 | return fetchConfig(); |
| 30 | }, |
| 31 | async profile() { |
| 32 | return fetchProfile((await |
| 33 | }, |
| 34 | }); |
| 35 | ``` |
| 36 | |
| 37 | **Alternative without extra dependencies:** |
| 38 | |
| 39 | We can also create all the promises first, and do `Promise.all()` at the end. |
| 40 | |
| 41 | ```typescript |
| 42 | const userPromise = fetchUser |
| 43 | const profilePromise = userPromise |
| 44 | |
| 45 | const [user, config |
| 46 | ``` |
| 47 | |
| 48 | Reference: [https://github.com/shuding/better-all](https://github.com/shuding/better-all |