556
Bn
bees-nest / files
bees-nest / .opencode / skills / vercel-react-best-practices / rules / async-dependencies.md
1.3 KB
1--- 2title: Dependency-Based Parallelization 3impact: CRITICAL 4impactDescription: 2-10× improvement 5tags: async, parallelization, dependencies, better-all 6--- 7 8## Dependency-Based Parallelization 9 10For 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 15const [user, config] = await Promise.all([ 16 fetchUser(), 17 fetchConfig() 18]) 19const profile = await fetchProfile(user.id) 20``` 21 22**Correct (config and profile run in parallel):** 23 24```typescript 25import { all } from 'better-all' 26 27const { 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 38We can also create all the promises first, and do `Promise.all()` at the end. 39 40```typescript 41const userPromise = fetchUser() 42const profilePromise = userPromise.then(user => fetchProfile(user.id)) 43 44const [user, config, profile] = await Promise.all([ 45 userPromise, 46 fetchConfig(), 47 profilePromise 48]) 49``` 50 51Reference: [https://github.com/shuding/better-all](https://github.com/shuding/better-all)