Skip to main content
rule CX Codex

async-defer-await — Claude Code rule: defer await operations

async-defer-await — a rule that moves await operations into code branches where they're actually needed, preventing blockage of execution paths that may exit early.

MIT ★ 7,191 updated 2026-10-24

Install into Claude Code · Manually: put the files in place All methods and platforms ↓
.claude/rules/async-defer-await.md
Open on GitHub

What async-defer-await does

When await sits at the start of a function, it blocks all paths until the result arrives—even if a branch returns before using it. This rule suggests moving await inside conditional branches so it triggers only when required.

Examples cover two patterns: a function with skipProcessing that exits without consuming data, and resource handling that checks existence before fetching permissions. In both, reordering operations provides a win—the code doesn't wait if the result won't be used.

The optimization matters when early exits fire often or when the deferred operation is costly (network call, database query). The rule integrates into Claude Code through .claude/rules/async-defer-await.md.

What it helps with

  • Avoid blocking code paths that may return before await completes
  • Reorder validation checks and conditions before async calls
  • Lower response time in functions with early returns
  • Defer expensive async operations until they're needed

Example prompts for the agent

  • Review handleRequest: the await blocks both branches, move it into the processing path only
  • Examine updateResource: fetch the resource first, defer permission checks to avoid blocking 404 cases
  • Identify all awaits that precede early returns and relocate them into their actual usage branches

How to install async-defer-await

Manually: put the files in place

.claude/rules/async-defer-await.md

The paths frontmatter field limits the files

Step by step, with commands for each platform: AGENTS.md vs CLAUDE.md: what they are and which one to use

Questions about async-defer-await

How do I install async-defer-await in Claude Code?

Create .claude/rules/async-defer-await.md in your project root with the rule content. Claude Code picks it up automatically on the next session.

What does this rule do?

It shows how to move await from the function top into branches where the result is actually consumed. Code runs faster because it skips waiting for unneeded operations.

When does this optimization matter?

When early exits happen frequently or when the deferred operation is expensive (HTTP request, database lookup). If all branches need the data, an early await is fine.

Source text

async-defer-await.md · MIT
---
title: Defer Await Until Needed
impact: HIGH
impactDescription: avoids blocking unused code paths
tags: async, await, conditional, optimization
---

## Defer Await Until Needed

Move `await` operations into the branches where they're actually used to avoid blocking code paths that don't need them.

**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)
}
```

**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)
}
```

This optimization is especially valuable when the skipped branch is frequently taken, or when the deferred operation is expensive.

© tech-leads-club · MIT · tech-leads-club/agent-skills

Similar IDE rules

All IDE rules for Backend and APIs →

From the same set130

The whole set →
client-localstorage-schema The client-localstorage-schema rule guides Claude Code to version localStorage keys and keep only fields the UI needs. Use it when changing client-side settings or cached user data. CX Codex +1 ★ 7,191repo stars client-event-listeners client-event-listeners — a Claude rule that keeps a single keydown listener on window no matter how many components call the shortcut hook. CX Codex +1 ★ 7,191repo stars server-after-nonblocking server-after-nonblocking instructs the agent to schedule logging, analytics, and cleanup with Next.js after(). This sends responses right away without waiting for background work. CX Codex +1 ★ 7,191repo stars rerender-lazy-state-init The rerender-lazy-state-init rule recommends lazy useState initialization for costly starting values. It helps when a React component reads stored settings or builds a data structure. CX Codex +1 ★ 7,191repo stars server-dedup-props server-dedup-props — a rule for Claude Code about React Server Components: RSC-to-client serialization deduplicates by reference, not value. Server-side transforms like toSorted or filter create new references and double the payload. CX Codex +1 ★ 7,191repo stars rendering-usetransition-loading rendering-usetransition-loading — a rule that swaps hand-rolled loading flags in React components for useTransition. Useful when a spinner runs on its own useState. CX Codex +1 ★ 7,191repo stars server-cache-react server-cache-react instructs the assistant to deduplicate server-side operations with React.cache() and prevent cache misses from inline object arguments. CX Codex +1 ★ 7,191repo stars architecture-avoid-boolean-props The architecture-avoid-boolean-props rule keeps component variants out of boolean props and moves them into composition. Use it when conditional UI branches start spreading across a component. CX Codex +1 ★ 7,191repo stars

Project sponsors

Companies that keep this analytics open