Async code
An unawaited promise rejects after your code has moved on—surfacing later as an unhandled rejection or crashing the process. Worse, reading a promise as if it were its resolved value silently produces wrong results. These habits eliminate both bug classes.
In short
awaitinsidetry: atryblock never catches a promise it doesn't await.- Handle errors inside callbacks: timers and event listeners run detached from the caller's
try. - Skip
forEach(async ...): usefor...ofwithawait, ormapLimitfor bounded concurrency. - Never treat a promise as a value:
awaitbefore passing toisErr, templates,!, orfilter. - Be intentional about background work:
awaitanything the next line needs; mark deliberate fire-and-forget calls withvoid. - Guard shared state across
await: re-read shared state after resuming, settle everynew Promiseon every path, and release acquired resources infinally.
1. await inside the try
✕ Rejectedfloating-rejection
ts
import { PropagateError } from "@evobug_com/safe-ts-std/result";
class Offline extends PropagateError {}
async function upload(file: string): Promise<void> {
if (file === "") throw new Offline("no connection");
}
export function save(file: string): void {
try {
upload(file);
} catch {
console.error("never runs: upload() rejects after this try has finished");
}
}✓ Accepted0 diagnostics
ts
import { PropagateError } from "@evobug_com/safe-ts-std/result";
class Offline extends PropagateError {}
async function upload(file: string): Promise<void> {
if (file === "") throw new Offline("no connection");
}
// The top of the `save` command: the one place that catches `Offline`.
export async function saveCommand(file: string): Promise<void> {
try {
await upload(file);
} catch (error) {
if (!(error instanceof Offline)) throw error;
console.error("offline, will retry");
}
}A PropagateError is for a failure that ends the whole command, so the try sits at its top. A failure the caller should handle is a value instead: return a Result, and await it like any other promise.
The same goes for library calls: await readFile(...) inside a try is handled, readFile(...) without await isn't. And for functions without the async keyword that return a promise (return upload(file), return fetchJson(url).then(...)): what matters is the promise, not the keyword. A rejection written as a call is a throw too: return Promise.reject(new Offline()), and reject(new Offline()) in a new Promise executor (also from a timer or listener inside it), reject the function's promise like throw in an async function.
2. Handle errors inside timers and event handlers
Timers, event handlers and promise callbacks run after the code that set them up has finished. An error inside them can't get back to that code, so handle it in the callback itself. The same holds for a function passed by name: in setInterval(refreshToken, 60_000), http.createServer(handle) or promise.then(refresh), refreshToken, handle and refresh are the top level, and catch there. A function passed by name is the arrow that calls it, wherever it goes. A callback you hand to one of your own functions is different when that function calls it right away (withRetry(() => load(id)), catchProtocol(() => decode(bytes))), also through a const copy of the parameter or by handing it on to another function that does: it runs inside the call, so a try around the call, or a catch in the function, handles it. An async function that calls it before its first await turns what it throws into its own rejection, handled where that promise is awaited. If the function keeps the callback for later, it is detached like a timer's.
✕ Rejecteduncaught-propagation
ts
import { PropagateError } from "@evobug_com/safe-ts-std/result";
class Expired extends PropagateError {}
function refreshToken(): string {
throw new Expired("session expired");
}
export function keepAlive(): ReturnType<typeof setInterval> {
return setInterval(() => {
refreshToken();
}, 60_000);
}✓ Accepted0 diagnostics
ts
import { PropagateError } from "@evobug_com/safe-ts-std/result";
class Expired extends PropagateError {}
function refreshToken(): string {
throw new Expired("session expired");
}
export function keepAlive(onExpired: () => void): ReturnType<typeof setInterval> {
return setInterval(() => {
try {
refreshToken();
} catch (error) {
if (!(error instanceof Expired)) throw error;
onExpired();
}
}, 60_000);
}3. Don't forEach with an async callback
forEach(async ...) starts every callback and returns straight away. Nobody waits for the promises, so their errors go nowhere.
✕ Rejecteduncaught-propagation
ts
import { PropagateError } from "@evobug_com/safe-ts-std/result";
class Offline extends PropagateError {}
async function upload(file: string): Promise<void> {
if (file === "") throw new Offline("no connection");
}
export function uploadAll(files: readonly string[]): void {
files.forEach(async (file) => {
await upload(file);
});
}✅ Accepted: one after another, or a few at a time
✓ Accepted0 diagnostics
ts
import { mapLimit } from "@evobug_com/safe-ts-std/async";
import { PropagateError, q, type Result } from "@evobug_com/safe-ts-std/result";
class Offline extends PropagateError {}
async function upload(file: string): Promise<void> {
if (file === "") throw new Offline("no connection");
}
export async function uploadInOrder(files: readonly string[]): Promise<void> {
for (const file of files) {
await upload(file);
}
}
export async function uploadTogether(files: readonly string[]): Promise<Result<void, unknown>> {
q(await mapLimit(files, 4, (file) => upload(file)));
return undefined;
}ts
import { mapLimit } from "@evobug_com/safe-ts-std/async";
import { Err as __qErr } from "@evobug_com/safe-ts-std/result"; import { PropagateError, q, type Result } from "@evobug_com/safe-ts-std/result";
class Offline extends PropagateError {}
async function upload(file: string): Promise<void> {
if (file === "") throw new Offline("no connection");
}
export async function uploadInOrder(files: readonly string[]): Promise<void> {
for (const file of files) {
await upload(file);
}
}
export async function uploadTogether(files: readonly string[]): Promise<Result<void, unknown>> {
{ const __q1 = await mapLimit(files, 4, (file) => upload(file)); if (__q1 instanceof __qErr) return __q1; __q1; }
return undefined;
}The first passes Offline on to its callers, who have to handle it. The second runs four uploads at a time and gives back the first failure as an Err (mapLimit catches it). Either way the error isn't lost any more. Promise.all(files.map(...)) would start every upload at once, however long the list (bounded-concurrency).
forEach(async ...) is reported even when nothing in it can fail (promise-as-value): the code after it runs before the callbacks finish.
4. A promise isn't its value
A promise is an object: always truthy, never undefined, [object Promise] as text. To std, a Promise<Result<T, E>> is even a Result (its value is the promise): isErr(load()) would always be false. std's types refuse that (this is a promise: await it, then pass the value), TypeScript refuses if (p) and p + 1, and promise-as-value reports the places TypeScript lets a promise through: a template, !p, p ?? x, p === undefined, an assertion in a test (expect(p).toBeTruthy() without .resolves, assert.ok(p): it passes whatever p resolves to), and an async function handed to what reads its answer right away (filter, some, find, a reduce step, a function of yours declared (item: T) => unknown).
❌ Rejected: the line says [object Promise], and every order passes
✕ Rejectedpromise-as-value
ts
async function paid(order: string): Promise<boolean> {
return order.endsWith("-paid");
}
async function total(orders: readonly string[]): Promise<number> {
return orders.length;
}
export function summary(orders: readonly string[]): string {
const open = orders.filter(async (order) => !(await paid(order)));
return `${open.length} open of ${total(orders)}`;
}✓ Accepted0 diagnostics
ts
async function paid(order: string): Promise<boolean> {
return order.endsWith("-paid");
}
async function total(orders: readonly string[]): Promise<number> {
return orders.length;
}
export async function summary(orders: readonly string[]): Promise<string> {
let open = 0;
for (const order of orders) if (!(await paid(order))) open++;
return `${open} open of ${await total(orders)}`;
}5. Start it, or await it
A promise dropped as a statement lets the caller go on before the work is done. When it can reject, that is floating-rejection; when it can't, floating-promise (a warning) asks which one you mean: await it where what follows needs it finished, or start it on purpose with void, wherever the statement is (a function of yours, a hook, a listener, a timer). An arrow that hands the promise back (() => reload()) and a function passed by name aren't statements, and aren't reported.
✅ Accepted: the list reloads in the background; the filter's handler has nothing more to do
✓ Accepted0 diagnostics
ts
async function reload(filter: string): Promise<void> {
await Promise.resolve();
console.log(`showing ${filter}`);
}
export function watchFilter(select: HTMLSelectElement, signal: AbortSignal): void {
select.addEventListener(
"change",
() => {
void reload(select.value);
console.log("filter changed");
},
{ signal },
);
}Latest run wins
A search box, a filter, a page that loads by id: a new run starts before the previous one answered, and the older answer can arrive last and overwrite the newer one. In a Vue or React component, useTask handles it (Vue, React). Without a framework (plain DOM code, a CLI, a worker), latest(...) from @evobug_com/safe-ts-std/async does the same without keeping a state:
✓ Accepted0 diagnostics
ts
import { latest, Superseded } from "@evobug_com/safe-ts-std/async";
import { type Enum, match } from "@evobug_com/safe-ts-std/enum";
import { isErr, type Result } from "@evobug_com/safe-ts-std/result";
type SearchError = Enum<{ Offline: {}; TooShort: { min: number } }>;
declare function searchUsers(query: string, signal: AbortSignal): Promise<Result<string[], SearchError>>;
export function mountSearch(input: HTMLInputElement, show: (text: string) => void, page: AbortSignal): void {
const search = latest((signal, query: string) => searchUsers(query, signal), page);
input.addEventListener(
"input",
async () => {
const names = await search.run(input.value);
if (!isErr(names)) return show(names.join(", "));
if (names.error instanceof Superseded) return; // a newer search brings the answer
show(
match(names.error, {
Offline: () => "You're offline",
TooShort: ({ min }) => `Type at least ${min} letters`,
}),
);
},
{ signal: page },
);
}- Each
run(...)aborts the previous run'ssignaland gives the new run a fresh one. Pass it to the request, so the older request stops instead of finishing unread (unused-task-signalreports a callback that doesn't). runresolves to what the work resolved to, or toerr(Superseded)when a newer run (orabort()) came first, whatever the older run resolved or rejected with.Supersededisn't a failure to show: the newer run brings the answer.- The second argument is the owner's signal (a page's, a dialog's): when it aborts, the run in progress is aborted and later
run(...)calls resolve toerr(Superseded)without starting. - The work reports failures in its
Result. A rejection of the latest run is a bug, as inuseTask:runrejects with it. - Return what the run found; don't write it somewhere yourself after an
await. The answer of a superseded run is dropped, but a write the callback makes itself isn't: it lands after the newer run's (superseded-task-write). When the callback must write, testsignal.abortedafter theawait, or hand the signal to the awaited call. - Create it where its owner lives (the function that mounts the screen, a component's setup, a page object), as above. One at module level is one run in progress for every caller: a second screen's run aborts the first one's.
no-mutable-globalreports it.
A hand-written ticket (const mine = ++latest; await ...; if (mine !== latest) return) is reported by latest-wins-counter (idiomatic): it drops the older answer, but the older request keeps running.
State across an await
Between two awaits nothing else runs, so reading and writing shared state there is safe. Across one, anything can: another call of the same method, a handler, a timer. A value read before the await is stale after it, and writing something made from it back loses what happened in between. stale-across-await reports it.
- Read after the
await:const p = await price(id); this.total += p;, notthis.total += await price(id)(JavaScript readsthis.totalfirst). The rule's quick fix writes it. - Check and claim before the first
await: a second caller must find the first one's work where it checks. Keep the promise in flight (this.loading.set(id, promise)before awaiting it), or set the flag right after testing it (if (this.stopping) return; this.stopping = true;). - The latest answer, not every answer: when only the newest run should write, that is latest run wins (
latest(...),useTask), a different question: the rule doesn't report a write of this run's own answer. - An event that happens once may happen meanwhile: a socket closes, a signal aborts, the page finishes loading. A listener for it added after the
awaitnever runs (late-listener): add it before the firstawait, or test what says it already happened (conn.closed,signal.aborted,document.readyState) after it.
A promise that settles, a resource that is released
Three more ways for async code to stop without an error:
- A
new Promisethat a path through its executor never settles:if (ready) resolve(value)with noelse, acatchthat only logs. Whatever awaits it waits forever (promise-never-settles). Settle it on every path, or handresolveto a timer or a listener that will. - A resource acquired before an
awaitand released after it: when theawaitrejects (or aq(...)returns the error), the release never runs, and the interval keeps firing, the file stays open (unreleased-resource). Release it in afinally, or declare it withawait usingwhere it is disposable. - A flag set before an
awaitand cleared after it (busy,saving): when theawaitrejects, the clearing never runs and the flag stays set for good, the button disabled (unbalanced-update). Clear it in afinally; in a component,useTaskholds the busy state itself.
Return a Result from async code
When the caller should handle the failure, return Promise<Result<T, E>>, just like Result in sync code. For Node's built-ins, the Node pack's safe versions already return a promise of a Result, with the error typed (text.error is a SystemError here, not unknown):
✓ Accepted0 diagnostics
ts
import { readFile } from "@evobug_com/safe-ts-feature-node/fs/promises";
import { isErr } from "@evobug_com/safe-ts-std/result";
import type { SafePath } from "@evobug_com/safe-ts-std/path";
export async function readOrDefault(path: SafePath, fallback: string): Promise<string> {
const text = await readFile(path, "utf8");
return isErr(text) ? fallback : text;
}✅ Also accepted: unsafeAsync around the original, for a promise no pack covers
✓ Accepted0 diagnostics
ts
import { readFile } from "node:fs/promises";
import { isErr, unsafeAsync } from "@evobug_com/safe-ts-std/result";
import type { SafePath } from "@evobug_com/safe-ts-std/path";
export async function readOrDefault(path: SafePath, fallback: string): Promise<string> {
const text = await unsafeAsync(() => readFile(path, "utf8"));
return isErr(text) ? fallback : text;
}unsafeAsync turns a promise that rejects into a Result too, with the error typed unknown.
Catch everything once at the entry point
Code that runs while a module loads has nothing above it to catch errors. Catch them once, at your entry point:
✓ Accepted0 diagnostics
ts
import { PropagateError } from "@evobug_com/safe-ts-std/result";
class Fatal extends PropagateError {}
async function main(): Promise<void> {
throw new Fatal("cannot start");
}
main().catch((error: unknown) => {
console.error(error);
process.exitCode = 1;
});Rules in this guide: floating-rejection, floating-promise, promise-as-value, uncaught-propagation, unhandled-failure