⏱ Timeout & Retry Made Fluent

⏱ Timeout & Retry Made Fluent — AsyncWhat.self()

In asynchronous workflows, handling timeouts and retries is often tedious, requiring nested try/catch blocks, timers, or promise orchestration. The self() method of AsyncWhat brings a declarative, chainable approach to these scenarios, making it intuitive to express robust asynchronous logic.


⏳ Timeout Mode

const fetchWithTimeout = AsyncWhat.as(fetch(url).then(res => res.text()))
  .self(2000);  // Timeout after 2 seconds

await fetchWithTimeout();
  • self(ms) wraps the current AsyncWhat in a timeout.
  • If the operation does not resolve within ms milliseconds, a TimeoutError is thrown.
  • Makes timeout behavior explicit in the chain without polluting the core logic.

๐Ÿ” Retry Mode

self(ms, nAttempts, baseDelay, factor) enables retries with exponential backoff:

const resilientFetch = AsyncWhat.as(fetch(url).then(res => res.text()))
  .self(1000, 3, 100, 2); // timeout 1s, 3 attempts, 100ms base delay, factor 2
  • nAttempts → how many times to retry.
  • baseDelay → initial delay before retry attempts.
  • factor → exponential growth of subsequent delays (delay = baseDelay * factor^i).
  • Parallel retries by default: each attempt is scheduled independently; first successful result resolves the chain.
  • Sequential retries are achievable: set baseDelay > timeout to enforce waiting for one attempt to finish before starting the next.

Example: Parallel vs Sequential

  • Parallel retries: multiple attempts fire in overlapping time windows. First success wins.
  • Sequential retries: achieved by making baseDelay > timeout; each attempt waits for the prior to fail.
ModeAttemptStart (ms)Duration (ms)Notes
Parallel Retries10200All attempts overlap partially

2100200

3200200
Sequential Retries10200Each attempt waits for delay

22500200

35000200

Benefits

  1. Readable — no nested try/catch or manual setTimeout wiring.
  2. Composable — integrates seamlessly with .sthen(), .else(), and other AsyncWhat chains.
  3. Flexible — choose parallel or sequential semantics via baseDelay and timeout.

By embracing AsyncWhat.self(), developers can express complex asynchronous patterns declaratively, focusing on the logic rather than the orchestration, and ensuring robust, fault-tolerant flows.


Comments

Popular posts from this blog

✨ Bridging Natural Language and Code

๐Ÿงฑ v0.0.0-dev.1

⚡ Early vs. Late Restriction