Deferred Promise Resolution Pattern

Core Concept

Create a Promise and extract its resolve function to control when the Promise resolves from outside its constructor:

// Step 1: Declare resolver outside Promise scope
let resolveClient: (client: ApiClient) => void;

// Step 2: Create Promise and capture resolver
const clientPromise = new Promise<ApiClient>(resolve => {
  resolveClient = resolve;  // Store resolver for external use
});

// Step 3: Resolve the Promise later from anywhere
setTimeout(() => {
  resolveClient(new ApiClient());  // Promise resolves here
}, 100);

Key Benefits

  • Decoupled Control: Resolve timing is controlled externally
  • No Race Conditions: All calls wait for the same Promise
  • Clean API: Consumers don't need to know about initialization state

This pattern is particularly useful for:

  • Lazy initialization
  • Dependency injection
  • Testing (control when mocks become available)
  • Breaking circular dependencies

Backlinks