Sub topic 7
Catching forgotten awaits
This chapter assumes you know async/await syntax, the Promise<T> type, and basic type narrowing. It covers what the compiler reports when you forget an await, what it misses, and how to close the gap with a linter.
What a forgotten await is
An await pauses an async function until a promise settles, then gives you the resolved value. If you leave it out, you keep the promise itself. Two different bugs follow from that:
- Wrong type in use. You treat
Promise<User>as if it wereUser. - Floating promise. You start an operation and drop the promise, so nobody observes whether it succeeds, fails, or finishes before the next line runs.
The compiler is good at the first bug and mostly blind to the second. The rest of the chapter follows from that split.
What the compiler catches
When the promise is stored in a variable and you use it as the resolved value, the types disagree and TypeScript reports an error.
declare function getUser(id: number): Promise<{ id: number; name: string }>;
async function greet(id: number): Promise<string> {
const user = getUser(id); // forgot await: user is Promise<{ id: number; name: string }>
return `Hello, ${user.name}`;
// error TS2339: Property 'name' does not exist on type 'Promise<...>'
}The same happens with arithmetic and with arguments:
declare function fetchLength(url: string): Promise<number>;
declare function takesNumber(n: number): void;
async function demo(url: string): Promise<void> {
const len = fetchLength(url);
takesNumber(len); // error: Promise<number> is not assignable to number
console.log(len + 1); // error: operator '+' cannot be applied to Promise<number> and number
}Conditions get a dedicated check. With strictNullChecks on (part of strict), an if over a promise is flagged because an object is always truthy.
declare function isAdmin(id: number): Promise<boolean>;
async function guard(id: number): Promise<void> {
if (isAdmin(id)) {
// error TS2801: This condition will always return true since this
// 'Promise<boolean>' is always defined. Did you forget to use 'await'?
console.log("admin");
}
}What the compiler does not catch
Some forgotten awaits produce no error at all.
Calls in statement position
If you call an async function and ignore the result, there is no type mismatch, because nothing consumes the value.
async function save(): Promise<void> {
// persist something
}
async function main(): Promise<void> {
save(); // compiles without complaint
console.log("saved"); // runs before save() has finished
}Two things go wrong here. The log line runs too early. And if save() rejects, the rejection has no handler. In Node.js 15 and later, an unhandled rejection terminates the process by default. Browsers report it to the console and continue.
Template strings and string conversion
Template literals accept any type, so a forgotten await produces garbage text instead of an error.
declare function getUser(id: number): Promise<{ id: number; name: string }>;
async function label(id: number): Promise<string> {
const user = getUser(id);
return `User: ${user}`; // compiles; the text is "User: [object Promise]"
}Callbacks that expect void
A function type that returns void accepts a function that returns anything, including a promise. So an async callback passes the type check where a synchronous one was expected.
const ids = [1, 2, 3];
async function remove(id: number): Promise<void> {
// delete something
}
ids.forEach(async (id) => {
await remove(id); // forEach ignores the returned promises
});
console.log("all removed"); // runs before any removal finishesReturning a promise inside try/catch
Inside try, return promise hands the promise to the caller before it settles, so a rejection skips your catch.
declare function loadText(): Promise<string>;
async function brokenLoad(): Promise<string> {
try {
return loadText(); // rejection bypasses the catch block
} catch {
return "fallback";
}
}
async function fixedLoad(): Promise<string> {
try {
return await loadText(); // rejection is caught here
} catch {
return "fallback";
}
}The return type is Promise<string> in both versions, so the compiler cannot tell them apart.
Closing the gap with typescript-eslint
The @typescript-eslint plugin has rules that use type information to find these mistakes. They need the linter to read your TypeScript project, so they are called type-aware rules. In ESLint's flat config format, turn them on like this:
// eslint.config.mjs
import tseslint from "typescript-eslint";
export default tseslint.config(
...tseslint.configs.recommendedTypeChecked,
{
languageOptions: {
parserOptions: {
projectService: true,
tsconfigRootDir: import.meta.dirname,
},
},
},
);The recommendedTypeChecked preset includes the rules in the table below. Type-aware linting is slower than plain linting because it builds the type graph for your project, so run it in CI as well as in the editor.
| Rule | What it flags |
|---|---|
| `no-floating-promises` | A promise-valued expression used as a statement with no `await`, `return`, `.catch(...)`, or `void` |
| `no-misused-promises` | A promise where a non-promise is expected: in an `if` condition, or an async function passed where a `void`-returning callback is expected (such as `forEach` or an event handler) |
| `await-thenable` | `await` applied to a value that is not a promise, which usually means a type is wrong or the await is useless |
| `require-await` | An `async` function that never uses `await`, often a sign that an await is missing |
| `return-await` | Inconsistent use of `return await`, configurable so that it is required inside `try` |
return-await is in the strict-type-checked preset rather than recommended-type-checked. If you want the try/catch protection shown earlier, enable it explicitly with "@typescript-eslint/return-await": ["error", "in-try-catch"].
How no-floating-promises decides
The rule looks at each expression statement. If the expression's type is a promise (or a thenable, meaning any object with a then method), the rule requires that it be handled in one of these ways.
Since I must follow the required fence format, here is the diagram in the correct form.
The following table shows what each form means in practice.
| Form | Meaning | Use when |
|---|---|---|
| `await save();` | Wait, and let errors propagate to the caller | You need the result or the ordering |
| `return save();` | Pass the promise to the caller | The function's job is to forward it (use `return await` inside `try`) |
| `save().catch(handle);` | Start it and handle failure | Fire-and-forget with logging |
| `void save();` | Deliberately ignore it | Only if errors are handled elsewhere |
A bare .then(f) with a single argument is still reported, because it creates a new promise that can reject and nothing handles it.
Marking intent with void
Sometimes you really do want to start work and not wait. An event handler cannot be async in a useful way, because the browser ignores the returned promise. The pattern is to combine void with .catch, so the intent is visible and failures are still reported.
async function save(): Promise<void> {
// persist something
}
function onClick(): void {
void save().catch((e: unknown) => console.error(e));
}The void operator tells readers and the linter that dropping the promise is intentional. The .catch is what stops a rejection from becoming unhandled. Using void alone silences the linter but does not handle errors, so prefer both together.
Fixing the forEach case
forEach never waits for its callback. Pick the form that matches the ordering you want.
declare function remove(id: number): Promise<void>;
// Sequential: one removal at a time
async function removeSequential(ids: number[]): Promise<void> {
for (const id of ids) {
await remove(id);
}
}
// Concurrent: all at once, wait for every one
async function removeConcurrent(ids: number[]): Promise<void> {
await Promise.all(ids.map((id) => remove(id)));
}for...of with await runs the calls in order. Promise.all over map starts them together and waits for all of them. Both are visible to the type system, and no-floating-promises accepts both.
Edge cases and limits
- Linting depends on types. If a value is typed
any, the rule cannot tell it is a promise, so a forgotten await on it goes unreported. Avoidanyat async boundaries. - Custom thenables. The rule treats any object with a callable
thenas a promise. If you have a type like that on purpose, you can list it underallowForKnownSafePromises. - Unawaited promises in arrays. Building an array of promises and never passing it to
Promise.allorallSettledis reported only if the array expression is itself a statement. If you store the array in a variable and forget it, no rule fires. - Unused result variables.
const p = save();withpnever read is caught byno-unused-vars, not by the floating-promise rule. - Tests. A test that does not return or await its async work can pass before the assertions run. Test runners generally need the test function to be
asyncor to return the promise.
Exercises
Exercise
The function below compiles and logs "done" immediately, even when the write fails. Name the rule that flags the problem and give a fix that keeps the caller informed of failures. async function writeAll(items: string[], write: (s: string) => Promise<void>): Promise<void> { items.forEach((item) => write(item)); console.log("done"); }
Show answer
@typescript-eslint/no-floating-promises flags write(item) inside the callback, because the returned promise is dropped. Fix it by awaiting inside a loop or using Promise.all: await Promise.all(items.map((item) => write(item))); placed before the log. Rejections then propagate to the caller of writeAll.
Exercise
Why does return loadText(); inside a try block fail to trigger the catch, and what single change fixes it?
Show answer
The function returns the promise to its caller without waiting for it, so the rejection happens after control has left the try block. Change it to return await loadText();. The return-await rule with the in-try-catch option enforces this.
Exercise
Which of these three mistakes does the TypeScript compiler report by itself with strict enabled: (a) const n = fetchLength(url); n.toFixed(); (b) fetchLength(url); as a statement (c) ` ${fetchLength(url)} `?
Show answer
Only (a). It fails with a property-does-not-exist error on Promise<number>. Case (b) compiles because the result is unused, and case (c) compiles because template literals accept any type. Both need the linter.