1.3 KiB
1.3 KiB
title, impact, impactDescription, tags
| title | impact | impactDescription | tags |
|---|---|---|---|
| Dependency-Based Parallelization | CRITICAL | 2-10× improvement | async, parallelization, dependencies, better-all |
基于依赖关系的并行化
对于存在部分依赖关系的操作,使用 better-all 来最大化并行度。它会自动让每个任务在最早可行的时刻启动。
错误做法(profile 不必要地等待 config):
const [user, config] = await Promise.all([
fetchUser(),
fetchConfig()
])
const profile = await fetchProfile(user.id)
正确做法(config 和 profile 并行运行):
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()。
const userPromise = fetchUser()
const profilePromise = userPromise.then(user => fetchProfile(user.id))
const [user, config, profile] = await Promise.all([
userPromise,
fetchConfig(),
profilePromise
])