필요한 시점까지 await 지연
Overview
Move await operations into the branches where they're actually used to avoid blocking code paths that don't need them.
Impact
- Priority: HIGH
- Performance: avoids blocking unused code paths
Problem
When you await async operations at the beginning of a function that aren't needed in all branches, you unnecessarily block code paths that don't use that data.
Incorrect (blocks both branches)
typescript
async function handleRequest(userId: string, skipProcessing: boolean) {
const userData = await fetchUserData(userId)
if (skipProcessing) {
// Returns immediately but still waited for userData
return { skipped: true }
}
// Only this branch uses userData
return processUserData(userData)
}When skipProcessing is true, we unnecessarily wait for fetchUserData.
Correct (only blocks when needed)
typescript
async function handleRequest(userId: string, skipProcessing: boolean) {
if (skipProcessing) {
// Returns immediately without waiting
return { skipped: true }
}
// Fetch only when needed
const userData = await fetchUserData(userId)
return processUserData(userData)
}Another Example (early return optimization)
typescript
// Incorrect: always fetches permissions
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)
}
// Correct: fetches only when needed
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)
}Key Points
- Only await where actually needed
- Leverage early return patterns
- Especially effective in frequently-taken branches
- Greater optimization effect for expensive operations
Use Cases
- Functions with conditional logic
- Operations requiring permission checks
- Functions with extensive error handling
- Early returns on cache hits
Tags: async, await, conditional, optimization