Sub topic 7
Catching Forgotten Awaits
Assume you know JavaScript promises, async and await, union types, and basic TypeScript generics. This chapter focuses on a common problem: starting asynchronous work without waiting for it or handling its rejection.
What is a floating promise?
A promise is floating when code creates it but does not await it, return it, or attach a rejection handler. The operation still starts, but the surrounding code cannot observe when it finishes or whether it fails.
async function save(): Promise<void> {
await new Promise((resolve) => setTimeout(resolve, 100));
throw new Error("Save failed");
}
async function updatePage(): Promise<void> {
save();
console.log("Page updated");
}
updatePage().catch((error: unknown) => {
console.error("Update failed:", error);
});updatePage prints Page updated immediately. The save promise is not connected to updatePage, so its rejection can become an unhandled rejection.
Usually, you should await the operation:
async function updatePage(): Promise<void> {
await save();
console.log("Page updated");
}Returning the promise is also valid when the caller should control it:
function updatePage(): Promise<void> {
return save();
}The return, await, or rejection handler makes the asynchronous control flow visible.
Why TypeScript may not warn you
The TypeScript compiler checks types, but it does not generally decide whether every promise must be consumed. This code is type-correct:
async function loadName(): Promise<string> {
return "Ada";
}
function showName(): void {
loadName();
}The call to loadName has type Promise<string>, and ignoring that value is allowed. The compiler cannot know whether the call is intentional, such as background logging, or accidental.
TypeScript can catch errors when a promise is used as the wrong value:
async function getCount(): Promise<number> {
return 3;
}
async function printCount(): Promise<void> {
const count: number = await getCount();
console.log(count);
}Without await, assigning getCount() to count: number would fail because Promise<number> is not number. The problem is harder to detect when the return value is simply discarded.
Marking intentional background work
Sometimes a function should start work without delaying the caller. Make that decision explicit, and handle rejection:
async function writeAuditLog(message: string): Promise<void> {
await new Promise((resolve) => setTimeout(resolve, 10));
console.log(message);
}
function onClick(): void {
void writeAuditLog("Button clicked").catch((error: unknown) => {
console.error("Could not write audit log:", error);
});
}
onClick();The void operator documents that the resolved value is intentionally ignored. It does not catch errors. The catch is still necessary.
A bare void writeAuditLog("Button clicked") can be appropriate only when the function is guaranteed not to reject, or when the application has another deliberate way to handle its failures.
Common mistakes in callbacks
An async callback passed to forEach does not make forEach wait:
async function processAll(ids: number[]): Promise<void> {
ids.forEach(async (id) => {
await save();
console.log(id);
});
console.log("Finished");
}Finished can print before any item completes. Use for...of for sequential work:
async function processAll(ids: number[]): Promise<void> {
for (const id of ids) {
await save();
console.log(id);
}
console.log("Finished");
}Use Promise.all when the operations can run concurrently:
async function processAll(ids: number[]): Promise<void> {
await Promise.all(
ids.map(async (id) => {
await save();
console.log(id);
}),
);
console.log("Finished");
}Lint rules that find floating promises
A type-aware ESLint setup can detect patterns that the compiler permits. The @typescript-eslint/no-floating-promises rule reports promises that are not awaited, returned, or handled. The @typescript-eslint/no-misused-promises rule reports an async function passed where a callback returning void is expected.
Configure these rules with your project’s TypeScript configuration:
{
"rules": {
"@typescript-eslint/no-floating-promises": "error",
"@typescript-eslint/no-misused-promises": [
"error",
{
"checksVoidReturn": true
}
]
}
}Use exceptions sparingly. A disabled warning can hide a real lost failure.
Exercise
Exercise
Rewrite this function so that it waits for every save operation and logs "Finished" only after all saves complete: async function run(ids: number[]): Promise<void> { ids.forEach(async () => { await save(); }); console.log("Finished"); }
Show answer
Use await Promise.all(ids.map(async () => { await save(); })); before the log, or use a for...of loop with await for sequential processing.