Reference
Programming languages Choose TypeScript, Go, Rust or C++ and find syntax, everyday APIs, standard libraries and tools in one place.
Scope and conventions TypeScript/Node, Go 1.23+, Rust 2024 and C++23: from a first CLI to files, JSON, HTTP, concurrency and testing. Complete programs are labeled; other examples identify their surrounding code/imports. Optional libraries and version requirements are named in each entry.
Async & concurrency TypeScript promises, Go goroutines/context, Rust futures with Tokio where named, and C++ threads/futures. Runtime and cancellation rules differ; optional setup is identified in each entry.
TypeScript
An async function starts immediately and runs synchronously until it suspends. Calling it returns a promise.
main.ts Follow appearance Follow appearance
✓ GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
Copy async function load() {
const response = await fetch("/api/items");
return response.json();
}
const pending = load();
TypeScript
await suspends the async function, not the JavaScript thread. A rejected promise throws at the await.
main.ts Follow appearance Follow appearance
✓ GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
Copy const value = await pending;
Retain ownership of a background task # TypeScript
Keep the promise and handle its outcome. void only discards the TypeScript value; it does not handle rejection.
main.ts Follow appearance Follow appearance
✓ GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
Copy const task = work();
void task.catch(reportError);
Sequential awaits versus overlapping work # TypeScript
Awaiting each call before starting the next is sequential. Create both promises first to overlap their pending work.
main.ts Follow appearance Follow appearance
✓ GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
Copy const left = loadLeft();
const right = loadRight();
const [a, b] = await Promise.all([left, right]);
Let other work progress # TypeScript
Awaiting an already resolved promise yields to promise jobs. It does not guarantee a browser paint or let queued timers run first.
Fragment
Long CPU work needs chunking with an appropriate scheduler or a worker.
main.ts Follow appearance Follow appearance
✓ GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
Copy
Wait for all successful results # TypeScript
Promise.all fulfills with input-order results or rejects on a rejection. Rejection does not cancel the other operations.
main.ts Follow appearance Follow appearance
✓ GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
Copy const values = await Promise.all(items.map(load));
Collect successes and failures # TypeScript
allSettled waits for every promise and returns a fulfilled/rejected record for each input.
main.ts Follow appearance Follow appearance
✓ GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
Copy const outcomes = await Promise.allSettled(tasks);
for (const outcome of outcomes) {
if (outcome.status === "fulfilled") use(outcome.value);
else reportError(outcome.reason);
}
Propagate async/task failures # TypeScript
catch handles a rejection; rethrow when the caller still owns recovery.
main.ts Follow appearance Follow appearance
✓ GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
Copy try {
await work();
} catch (error) {
reportError(error);
throw error;
}
Clean up after asynchronous work # TypeScript
finally runs after success or failure of the try block. Await cleanup if the cleanup itself is asynchronous.
main.ts Follow appearance Follow appearance
✓ GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
Copy const resource = await acquire();
try {
await use(resource);
} finally {
await resource.close();
}
TypeScript
AbortController signals cooperating APIs such as Fetch. It cannot forcibly stop arbitrary promise or CPU work.
main.ts Follow appearance Follow appearance
✓ GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
Copy const controller = new AbortController();
const task = fetch(url, { signal: controller.signal });
controller.abort();
// Await/catch task in its owner.
Bound the duration of work # TypeScript
AbortSignal.timeout supplies a timed signal in supporting runtimes. The called API must honor it.
Fragment
Availability depends on the browser/Node version. A timeout does not prove a server write failed.
main.ts Follow appearance Follow appearance
✓ GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
Copy const response = await fetch(url, {
signal: AbortSignal.timeout(3000)
});
Wait for the first completion # TypeScript
race settles with the first settled input. any fulfills on the first fulfillment and rejects if all reject. Neither cancels losers.
main.ts Follow appearance Follow appearance
✓ GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
Copy const first = await Promise.race(tasks);
const firstSuccess = await Promise.any(tasks);
Delay work with the runtime’s timer model # TypeScript
A timer resolves later; the actual delay can exceed the requested interval.
main.ts Follow appearance Follow appearance
✓ GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
Copy await new Promise<void>(resolve => setTimeout(resolve, 100));
Send a value through a channel # TypeScript
Promises represent one eventual settlement. For multiple messages use a stream, async iterator or an explicitly chosen channel library.
main.ts Follow appearance Follow appearance
✓ GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
Copy async function* values() {
yield 1;
yield 2;
}
Distinguish channel closure from a value # TypeScript
An async iterator uses done: true to indicate completion; return() may support cleanup depending on the iterator.
main.ts Follow appearance Follow appearance
✓ GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
Copy const step = await iterator.next();
if (!step.done) use(step.value);
Recognize a backpressure boundary # TypeScript
Awaiting the consumer can limit producer progress; precreating every promise can still start unbounded work.
main.ts Follow appearance Follow appearance
✓ GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
Copy for await (const item of source) {
await consume(item);
}
Consume a stream incrementally # TypeScript
A for-await loop consumes async-iterable values. The iterator defines cleanup and cancellation behavior.
main.ts Follow appearance Follow appearance
✓ GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
Copy for await (const chunk of source) {
process(chunk);
}
Limit concurrent operations # TypeScript
Start a fixed number of workers rather than mapping every item to a promise at once.
Fragment
This single-agent counter relies on no await between reading/incrementing next. Define how worker failure stops the others.
main.ts Follow appearance Follow appearance
✓ GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
Copy let next = 0;
async function worker() {
while (next < items.length) {
const index = next++;
await process(items[index]);
}
}
await Promise.all(Array.from({ length: 4 }, worker));
Protect a shared invariant # TypeScript
Single-threaded JavaScript still has logical races across await. Use an owner queue, transaction or a defined locking library when a multi-step invariant must be serialized.
Fragment
There is no standard Promise mutex API equivalent to sync.Mutex.
main.ts Follow appearance Follow appearance
✓ GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
Copy const before = state.value;
await something();
// state.value may have changed before this continuation.
Move blocking or CPU-heavy work appropriately # TypeScript
Async syntax does not move CPU work off the JavaScript thread. Use a Web Worker or Node worker_threads for suitable CPU tasks.
main.ts Follow appearance Follow appearance
✓ GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
Copy // Browser:
const worker = new Worker(new URL("./worker.js", import.meta.url));
worker.postMessage(input);
Separate shared ownership from synchronization # TypeScript
SharedArrayBuffer exposes memory shared with workers; Atomics provides synchronization on supported integer views.
Fragment
Browser use has cross-origin isolation requirements. Ordinary object sharing is not the same mechanism.
main.ts Follow appearance Follow appearance
✓ GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
Copy const view = new Int32Array(new SharedArrayBuffer(4));
Atomics.add(view, 0, 1);
Keep child work inside an owned lifetime # TypeScript
Promise.all joins promises but does not create a cancellation scope. Define who aborts, waits for and reports every child.
main.ts Follow appearance Follow appearance
✓ GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
Copy const controller = new AbortController();
// Pass its signal to every cooperating child.
// On failure: abort, then observe remaining outcomes.
Establish the runtime and API baseline # TypeScript
Promises are runtime values; TypeScript’s lib settings describe types rather than installing APIs. Promise.any requires an ES2021-capable runtime; AbortSignal helpers depend on the host version.
Fragment
This is a Node entry point. Browsers do not provide process. Check supported Web/Node APIs separately from compiler target.
main.ts Follow appearance Follow appearance
✓ GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
Copy async function main() {
await Promise.resolve();
}
void main().catch(error => {
console.error(error);
process.exitCode = 1;
});
Cancel cooperating siblings and observe completion # TypeScript
Promise.all fails early without canceling siblings. Pass one signal to cooperating tasks, abort on failure, then observe every outcome before the owner exits.
Fragment
work must return a promise and honor the signal. A task that never settles can still keep allSettled waiting; define a larger owner deadline.
main.ts Follow appearance Follow appearance
✓ GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
Copy const controller = new AbortController();
const tasks = items.map(item =>
Promise.resolve().then(() => work(item, controller.signal))
);
try {
await Promise.all(tasks);
} catch (error) {
controller.abort();
await Promise.allSettled(tasks);
throw error;
}
Bound task records and consume results while launching # TypeScript
A worker pool can consume each result before claiming another item. Avoid retaining one promise/output per input when the input can be large.
Fragment
This example reserves undefined as the end marker and assumes a synchronous takeNext owner; define another protocol when undefined is valid data.
main.ts Follow appearance Follow appearance
✓ GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
Copy async function worker() {
for (;;) {
const item = takeNext();
if (item === undefined) return;
await consume(await work(item));
}
}
await Promise.all(Array.from({ length: 4 }, worker));
Account for progress when a wait is canceled # TypeScript
Aborting a pending API call does not undo bytes already sent, an accepted server operation or a consumed stream chunk. Make retry decisions using the operation’s own progress contract.
main.ts Follow appearance Follow appearance
✓ GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
Copy const controller = new AbortController();
const pending = fetch(url, { signal: controller.signal });
controller.abort();
await pending.catch(handleAbortOrFailure);