--- title: Defer Await Until Needed impact: HIGH impactDescription: 避免阻塞不需要的代码路径 tags: async, await, conditional, optimization --- ## 将 await 延迟到真正需要时 将 `await` 操作移到实际使用它的分支中,以避免阻塞不需要它的代码路径。 **错误写法(两个分支都被阻塞):** ```typescript async function handleRequest(userId: string, skipProcessing: boolean) { const userData = await fetchUserData(userId) if (skipProcessing) { // 立即返回,但仍然等待了 userData return { skipped: true } } // 只有这个分支使用了 userData return processUserData(userData) } ``` **正确写法(只在需要时阻塞):** ```typescript async function handleRequest(userId: string, skipProcessing: boolean) { if (skipProcessing) { // 立即返回,无需等待 return { skipped: true } } // 只在需要时才获取 const userData = await fetchUserData(userId) return processUserData(userData) } ``` **另一个示例(提前返回优化):** ```typescript // 错误写法:总是获取权限 async function updateResource(resourceId: string, userId: string) { const permissions = await fetchPermissions(userId) const resource = await getResource(resourceId) if (!resource) { return { error: 'Not found' } } if (!permissions.canEdit) { return { error: 'Forbidden' } } return await updateResourceData(resource, permissions) } // 正确写法:只在需要时才获取 async function updateResource(resourceId: string, userId: string) { const resource = await getResource(resourceId) if (!resource) { return { error: 'Not found' } } const permissions = await fetchPermissions(userId) if (!permissions.canEdit) { return { error: 'Forbidden' } } return await updateResourceData(resource, permissions) } ``` 当被跳过的分支经常被执行,或延迟操作开销很大时,此优化尤为有价值。 对于 `await getFlag()` 与廉价同步守卫(`flag && someCondition`)组合使用的情况,请参阅 [先检查廉价条件,再处理异步标志](./async-cheap-condition-before-await.md)。