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.

Create async work

TypeScript

An async function starts immediately and runs synchronously until it suspends. Calling it returns a promise.

Fragment

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
async function load() {
  const response = await fetch("/api/items");
  return response.json();
}
const pending = load();

Wait for a value

TypeScript

await suspends the async function, not the JavaScript thread. A rejected promise throws at the await.

Fragment

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
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.

Fragment

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
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.

Fragment

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
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
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
await Promise.resolve();

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.

Fragment

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
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.

Fragment

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
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.

Fragment

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
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.

Fragment

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const resource = await acquire();
try {
  await use(resource);
} finally {
  await resource.close();
}

Request cancellation

TypeScript

AbortController signals cooperating APIs such as Fetch. It cannot forcibly stop arbitrary promise or CPU work.

Fragment

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
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
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
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.

Fragment

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
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.

Fragment

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
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.

Fragment

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
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.

Fragment

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
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.

Fragment

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
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.

Fragment

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
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
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
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
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
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.

Fragment

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
// 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
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
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.

Fragment

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
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
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
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
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
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
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
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.

Fragment

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
const controller = new AbortController();
const pending = fetch(url, { signal: controller.signal });
controller.abort();
await pending.catch(handleAbortOrFailure);