๐ Infinite Cycles & Controlled Retries — AsyncWhat.self()
๐ Infinite Cycles & Controlled Retries — AsyncWhat.self()
In asynchronous workflows, retries and repeated executions are a common pattern — but there’s a subtle yet powerful distinction: whether you await
a function or not completely changes its behavior.
Understanding this allows you to implement both controlled retries and infinite cycles using the same retry logic provided by AsyncWhat.self()
.
⏳ Sequential Retries (Finite Attempts)
When you want a function to retry several times before giving up, you typically await
its result:
const task = async () => {
const res = await fetch(url);
if (!res.ok) throw new Error("Fetch failed");
return res.text();
}
const resilient = AsyncWhat.as(task).self(3, 100, 2); // 3 attempts, 100ms base, exponential backoff
const result = await resilient(); // <-- await is key
console.log("Final result:", result);
How it works
resilient()
returns a promise immediately, butawait
pauses your async flow until:- the task succeeds,
- the maximum number of attempts is reached, or
- the retry process is explicitly stopped.
Each failure schedules the next retry after a calculated backoff delay:
delay = min(baseDelay * factor^attemptIndex, maxDelay)
- The retry mechanism triggers automatically when the task throws or returns
undefined
.
♾ Infinite Cycles
Sometimes you want a task to run indefinitely — for polling, heartbeats, or continuous monitoring. Typically, such a task is a procedure (returns undefined
) that performs side effects rather than producing a value.
const task = () => console.log("Tick", new Date().toISOString()); // procedure returning undefined
const infiniteLoop = AsyncWhat.as(task).self(Infinity, 100, 1); // never ends: the task never resolves and retries forever
The crucial distinction when calling infiniteLoop()
:
- Without
await
:
infiniteLoop(); // starts the infinite cycle immediately
console.log("This prints immediately"); // main flow continues; the loop runs asynchronously
- With
await
:
await infiniteLoop(); // pauses the current async flow until stopped
console.log("This never prints");
๐ Key Takeaways
Behavior | How to call | Notes |
---|---|---|
Finite retries | await resilient() | Waits until success or all attempts fail. |
Infinite cycles | infiniteLoop() (no await) | Runs continuously; main thread remains free. |
An async function like infiniteLoop
does not need to be awaited to execute. This means you can launch an infinite cycle safely without blocking your main program or event loop.
By mastering this await / no-await distinction, you can treat infinite cycles as a natural extension of retry logic — simply by not awaiting and using infiniteLoop.stopped = true
to gracefully stop them.
— @fizzwiz ✨
Comments
Post a Comment