⏱ 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 currentAsyncWhat
in a timeout.- If the operation does not resolve within
ms
milliseconds, aTimeoutError
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.
Mode | Attempt | Start (ms) | Duration (ms) | Notes |
---|---|---|---|---|
Parallel Retries | 1 | 0 | 200 | All attempts overlap partially |
2 | 100 | 200 | ||
3 | 200 | 200 | ||
Sequential Retries | 1 | 0 | 200 | Each attempt waits for delay |
2 | 2500 | 200 | ||
3 | 5000 | 200 |
Benefits
- Readable — no nested
try/catch
or manualsetTimeout
wiring. - Composable — integrates seamlessly with
.sthen()
,.else()
, and other AsyncWhat chains. - Flexible — choose parallel or sequential semantics via
baseDelay
andtimeout
.
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
Post a Comment