TypeScript · Lesson 11
Advanced async TypeScript
Typing async code precisely, async iterators and generators, race conditions without threads, using / await using, single-flight caching, backpressure and structured concurrency, with how React, Angular, cloud SDKs and F# handle the same problems.
In short
- Async callbacks in
forEachare never awaited - Async generators are lazy, pull-based and clean up on
break - Every
awaitis a point where other code can run - Single-flight: cache the promise, not the value
usingdisposes in reverse order, however the block exits
The Event loop & async topic covered how one thread juggles timers and promises, and the everyday helpers (timeouts, debounce, retries, concurrency limits). This topic is about what comes after that: typing async code precisely, and coordinating many async operations safely. That means streams of results, shared state, shared requests, producers that are faster than consumers, and groups of tasks that must start and stop together.
As before, every TypeScript snippet has a ▶ Try button. Predict, then run.
Typing async code
An async function always returns a Promise, and promises never nest. Returning a promise from an
async function gives you Promise<T>, not Promise<Promise<T>>. Awaited<T> is the type-level version of await: it
unwraps promises recursively.
async function getUser() {
return { id: '42', name: 'Ann' };
}
type UserPromise = ReturnType<typeof getUser>; // Promise<{ id: string; name: string }>
type User = Awaited<ReturnType<typeof getUser>>; // { id: string; name: string }
type Deep = Awaited<Promise<Promise<number>>>; // number
const u: User = { id: '7', name: 'Bo' };
console.log(u.name);
Awaited<ReturnType<typeof fn>> is the standard way to name "what this API call gives me" without writing the
type twice.
Errors are untyped. Promise<T> says nothing about how it can fail, and with strict on, a catch (e)
variable is unknown. Narrow before you use it:
class HttpError extends Error {
override name = 'HttpError';
constructor(readonly status: number) {
super(`HTTP ${status}`);
}
}
const isAbort = (e: unknown) => e instanceof Error && (e.name === 'AbortError' || e.name === 'TimeoutError');
async function load(): Promise<string> {
throw new HttpError(404);
}
load().catch((e: unknown) => {
if (isAbort(e)) return; // the user navigated away: not an error
if (e instanceof HttpError && e.status === 404) console.log('not found');
else throw e;
});
When failure is part of the normal flow (validation, "not found"), returning a Result<T, E> union makes the
error type visible to the compiler. The Functional patterns topic covers that.
The void callback trap. A function returning a Promise is assignable to one returning void, so this
compiles but does not wait:
const wait = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
async function saveAll(ids: number[]) {
ids.forEach(async (id) => {
await wait(10);
console.log('saved', id);
});
console.log('all saved?'); // printed first: forEach ignored the promises
}
saveAll([1, 2, 3]);
Use for (const id of ids) await save(id) (one at a time) or await Promise.all(ids.map(save)) (all at
once). The @typescript-eslint/no-misused-promises and no-floating-promises lint rules catch this whole family
of mistakes, and they're worth turning on in any React or Angular codebase.
Async iteration
An async iterable is anything with a [Symbol.asyncIterator]() method that returns an object whose
next() returns Promise<{ value, done }>. for await consumes it, and an async function* (an async
generator) is the easy way to write one:
async function* numbers() {
try {
for (let i = 1; ; i++) {
console.log('produce', i);
yield i;
}
} finally {
console.log('cleanup'); // runs when the consumer stops
}
}
async function main() {
for await (const n of numbers()) {
console.log('consume', n);
if (n === 2) break;
}
console.log('done');
}
main();
Three properties make async iterables the right tool for streams of results:
- Lazy and pull-based. The generator only runs while the consumer asks for the next value. A slow consumer is never flooded, and an infinite source is fine.
- Cleanup is built in.
break,returnor athrowin the loop calls the iterator'sreturn(), which runs the generator'sfinally. That's where you close the connection or release the receiver. - Typed end to end.
AsyncGenerator<T, TReturn, TNext>andAsyncIterable<T>carry the item type through every stage of a pipeline.
You'll meet them in cloud SDKs (AWS SDK v3 paginators such as paginateListObjectsV2, Azure's
container.listBlobsFlat(), Google Cloud's list...Async() methods) and message-queue receivers, in Node
streams and readline, and in fetch response bodies
(ReadableStream is async iterable in Node and recent browsers).
Race conditions without threads
JavaScript never runs two pieces of your code at the same time, but every await is a point where other
code can run. A read-await-write sequence can interleave with another one:
const wait = (ms: number) => new Promise<void>((r) => setTimeout(r, ms));
let balance = 100;
async function withdraw(amount: number) {
const current = balance; // both calls read 100
await wait(10); // ...the other call runs here...
balance = current - amount;
}
async function main() {
await Promise.all([withdraw(30), withdraw(50)]);
console.log('balance', balance); // 50, not 20: one withdrawal was lost
}
main();
The usual shapes and their fixes:
| Bug | Example | Fix |
|---|---|---|
| Lost update (read, await, write) | balance, counters, a JSON file | a mutex around the section, or an atomic operation on the server |
| Check-then-act (if missing, fetch) | 5 components fetch the same user | single-flight: cache the promise, not the value |
| Stale response wins | search results for an old query | ignore everything but the latest call (switchMap, AbortController) |
| Two processes, one record | two serverless instances update an order | optimistic concurrency: an ETag or version number + a conditional write (If-Match) |
A mutex only protects one process. Across browser tabs, use navigator.locks. Across servers, let the database
decide (ETags, transactions, a unique constraint) or use a lease.
using and await using
TypeScript 5.2 added explicit resource management: a using declaration calls the value's
[Symbol.dispose]() when the block exits, however it exits. await using does the same with
[Symbol.asyncDispose](), which it awaits. Resources are disposed in reverse order, like nested try/finally
blocks you can't forget to write.
function open(name: string): Disposable {
console.log('open', name);
return { [Symbol.dispose]: () => console.log('close', name) };
}
function openAsync(name: string): AsyncDisposable {
console.log('open', name);
return {
[Symbol.asyncDispose]: async () => {
await Promise.resolve();
console.log('close', name);
},
};
}
async function handle() {
await using conn = openAsync('db connection');
using lock = open('lock');
console.log('work');
throw new Error('something failed'); // both are still released, lock first
}
handle().catch((e: Error) => console.log('caught:', e.message));
It's the same idea as C#'s using and F#'s use. Good candidates: locks, database connections, temporary
files, subscriptions, performance marks, and anything else with a close() you must not forget. In the lab it
works out of the box. In a real project you need TypeScript 5.2+ and lib: ["esnext.disposable"] (or
esnext), plus a runtime with Symbol.dispose (Node 20+, and recent Chrome and Firefox; Safari doesn't ship it
yet, so add a polyfill such as core-js's).
Push vs pull: picking the right abstraction
| values | who's in control | cancellation | typical use | |
|---|---|---|---|---|
Promise<T> | one | producer (eager) | AbortSignal | one request |
AsyncIterable<T> | many | consumer pulls | break / return() | pages, streams, queues |
RxJS Observable<T> | many | producer pushes | unsubscribe() | UI events, Angular HttpClient, websockets |
EventTarget / callbacks | many | producer pushes | removeEventListener | DOM, low-level APIs |
Push sources need a plan for when they're faster than you. That plan is backpressure (make the producer
wait), or a policy: buffer, drop, sample, debounce. Pull sources get backpressure for free. The AsyncQueue
exercise is the bridge: callbacks push into it, and a for await loop pulls out of it.
Cancellation that composes
Every layer should accept an AbortSignal and pass it on. Combine signals instead of inventing flags:
const user = new AbortController(); // e.g. the component unmounted
const signal = AbortSignal.any([user.signal, AbortSignal.timeout(50)]);
signal.addEventListener('abort', () => console.log('aborted because:', (signal.reason as Error).name));
const work = new Promise<string>((resolve, reject) => {
const timer = setTimeout(() => resolve('finished'), 200);
signal.addEventListener('abort', () => {
clearTimeout(timer);
reject(signal.reason);
});
});
work.then(console.log, (e: Error) => console.log('work stopped:', e.name));
Structured concurrency takes this one step further: tasks belong to a scope, a failure cancels its siblings, and the scope only finishes when every task has finished. Nothing keeps running unobserved after an error. The last exercise builds one.
In React
use(promise)and Suspense (React 19) suspend a component until a promise settles. The promise must be the same object on every render, so create it in a cache (the single-flight exercise) or let a framework or data library do it. Never create it during render.- TanStack Query (or SWR, RTK Query) is single-flight + TTL + invalidation + retries in one library. Use the
query key the way the exercise uses
key,staleTimethe way it usesttlMs, andinvalidateQueriesafter mutations. - Effects are scopes. Create an
AbortControllerin the effect, passcontroller.signaldown, and abort in the cleanup. That's structured concurrency at the component level.
In Angular
- RxJS is Angular's async workhorse:
switchMap(latest only),mergeMap(fn, n)(concurrency limit),shareReplay(1)(share one request),retry,takeUntilDestroyed()(scope to the component).firstValueFrom(obs$)andlastValueFrom(obs$)turn an Observable into a promise when you needawait. - Signals-based async.
resource()andhttpResource()in newer Angular versions load data into signals, pass the loader anabortSignal, and cancel stale loads when their inputs change.toSignal(obs$)bridges Observables into signals. - Interceptors are where single-flight shows up most: one token refresh shared by every request that got a
401.
On the server and in the cloud
- Page through results with
for awaitover the SDK's paginator, and keep the continuation token (NextToken,pageToken,continuationToken, depending on the API) to resume later. - Bound your concurrency (
mapLimit), your buffers (the prefetch and max-concurrency settings on a queue consumer), and your waiting (AbortSignal.timeout). - In serverless functions (AWS Lambda, Azure Functions, Google Cloud Run functions), pass the invocation's cancellation or timeout down to every call, and never leave floating promises. The host considers the invocation finished when your handler's promise settles.
- In-memory locks and caches are per instance. With several instances, coordinate through the data store: ETags, leases, idempotency keys.
F# for comparison
Side note
F#'s MailboxProcessor is an agent: an async queue (like the AsyncQueue exercise) with a single consumer
loop that owns its state. Only the agent touches the state, so it needs no mutex.
type Msg =
| Add of int
| Get of AsyncReplyChannel<int>
let counter =
MailboxProcessor.Start(fun inbox ->
let rec loop total = async {
match! inbox.Receive() with
| Add n -> return! loop (total + n)
| Get reply ->
reply.Reply total
return! loop total }
loop 0)
for i in 1 .. 100 do counter.Post(Add i)
printfn "total = %d" (counter.PostAndReply Get)
useis F#'susing. In anasync { }ortask { }block,use!binds and disposes an async resource.- Async sequences come from libraries:
taskSeq { }(FSharp.Control.TaskSeq) andAsyncSeqare the F# versions of async generators. CancellationTokenflows throughasync { }automatically. That's F#'s answer to passingAbortSignaleverywhere.
The exercises
- Clean up with using: listeners, intervals and timeout signals that remove themselves when the block ends.
- Lazy pagination: an async generator over a paged API that stops fetching when you stop reading.
- Async iterable pipelines:
mapAsync,filterAsync(with type-predicate overloads),takeandbatch, with cleanup that reaches the source. - Mutex with using: fix the lost update, with FIFO fairness, abortable waits and
Symbol.dispose. - Single-flight cache with TTL: share in-flight requests, never cache failures, and handle invalidation races.
- AsyncQueue with backpressure: a bounded channel between callbacks and
for await. - Structured concurrency: a task group that cancels siblings on failure and never leaves orphans.
Practise this lesson
In the app: a short video, 7 exercises checked by real tests and a 12-question concept check. Free with a GitHub account.
Open in the app