Skip to content
Tutorials Center
My learning

Topics

Lesson 7 of 37 ยท Language and Runtime Basics

Async Code and Top-Level Await

Write asynchronous Deno code with promises and async/await, use top-level await in modules, run tasks in parallel, handle timeouts and cancellation, and meet the @std/async helpers.

Nearly everything a Deno program does that talks to the outside world is asynchronous: reading files, calling an API, waiting for a request. Deno's APIs return promises, and the language gives you async and await to use them. What makes Deno pleasant is that ES modules allow top-level await, so a script can await straight away, with no main() wrapper.

This lesson covers the patterns you will use every day: sequential and parallel work, error handling, timeouts, cancellation and retries. The ideas are standard JavaScript, so the runnable examples work the same in Deno.

Top-level await

In Deno every file is an ES module, so await is allowed at the top level:

TypeScript
const text = await Deno.readTextFile("./notes.txt");
console.log(text.length);

const res = await fetch("https://example.com/data.json");
const data = await res.json();

The module does not finish loading until each top-level await completes. If another module imports this one, it waits too, which is exactly what you want for setup such as loading configuration. Be careful in a library: a slow top-level await delays everything that imports it, so keep it for entry points.

Node.js Top-level await in a module

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Sequential and parallel

Two awaits in a row run one after the other. If the calls do not depend on each other, start them together and wait once:

Node.js Sequential vs parallel timing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The four combinators you should know:

Function Resolves when Rejects when
Promise.all all fulfil any rejects (fast)
Promise.allSettled all finish never
Promise.race the first settles the first settles with an error
Promise.any the first fulfils all reject

Use allSettled when partial success is fine, such as fetching ten optional resources.

Handling errors

try/catch works around await:

TypeScript
try {
  const data = await Deno.readTextFile("config.json");
  console.log(JSON.parse(data));
} catch (error) {
  console.error("could not load config:", error);
  Deno.exit(1);
}

A promise that rejects with no handler is an unhandled rejection. In Deno that terminates the program with an error and exit code 1, which is safer than Node's historic warning. If you start a promise and do not await it, attach a .catch() so the failure goes somewhere:

TypeScript
sendMetrics().catch((e) => console.error("metrics failed", e));

Timeouts and cancellation

Web APIs use AbortSignal for cancellation, and Deno's own APIs accept signals too. AbortSignal.timeout(ms) makes a signal that fires automatically:

TypeScript
try {
  const res = await fetch("https://example.com/slow", {
    signal: AbortSignal.timeout(3000),
  });
  console.log(res.status);
} catch (error) {
  if (error instanceof DOMException && error.name === "TimeoutError") {
    console.log("took too long");
  } else {
    throw error;
  }
}

Here is the same idea with a function you write yourself, so you can run it:

Node.js Timeout with AbortSignal

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

AbortSignal.any([a, b]) combines signals, so an operation stops on a timeout or a user's cancel. Streams also honour signals.

Async iteration

Many Deno APIs produce a series of values over time as async iterables. You consume them with for await:

TypeScript
for await (const entry of Deno.readDir(".")) {
  console.log(entry.name, entry.isFile);
}

const file = await Deno.open("big.log");
for await (const chunk of file.readable) {
  console.log(`read ${chunk.length} bytes`);
}

You can write your own with async function*:

Node.js An async generator

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The @std/async helpers

The standard library adds small tools that save you from writing them yourself. Import from JSR:

TypeScript
import { delay } from "jsr:@std/async@1/delay";
import { retry } from "jsr:@std/async@1/retry";
import { debounce } from "jsr:@std/async@1/debounce";
import { pooledMap } from "jsr:@std/async@1/pool";

await delay(500); // like sleep

// Retry with exponential backoff and jitter
const body = await retry(async () => {
  const res = await fetch("https://example.com/flaky");
  if (!res.ok) throw new Error(`status ${res.status}`);
  return res.text();
}, { maxAttempts: 4 });

// Process many items, at most 3 at a time
const results = pooledMap(3, urls, (url) => fetch(url));
for await (const res of results) {
  console.log(res.status);
}

The idea behind retry is easy to implement, and a good exercise:

Node.js A tiny retry helper

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

In real code add a delay that grows between attempts, and only retry errors that are worth retrying (timeouts, 5xx), never errors caused by bad input.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why can a Deno script use await outside a function?

    ES modules support top-level await, and every Deno file is a module.
  2. 2. You need results from three independent requests. What is fastest?

    Promise.all starts them together, so total time is the slowest request rather than the sum.
  3. 3. Which combinator never rejects?

    allSettled waits for every promise and reports each outcome as fulfilled or rejected.
  4. 4. What happens to an unhandled promise rejection in Deno?

    Deno treats unhandled rejections as fatal errors, which exposes bugs early.
  5. 5. What does AbortSignal.timeout(3000) create?

    It returns an AbortSignal that aborts itself with a TimeoutError after the delay.

Summary

  • Top-level await works in every Deno module; use it in entry points.
  • Use Promise.all for independent work and allSettled when partial results are fine.
  • Unhandled rejections stop the program; attach .catch() to fire-and-forget promises.
  • AbortSignal.timeout and AbortSignal.any add timeouts and cancellation.
  • for await consumes async iterables; async function* creates them.
  • @std/async offers delay, retry, debounce and pooledMap.

Next: Reading and Writing Files