Skip to content
jshacks.dev
Async

How to Detect Unawaited Promises With Lint Rules

Detect unawaited promises with typescript-eslint no-floating-promises and no-misused-promises, set them up for JavaScript projects and fix what they report.

7 min read
Summarize in AI
Flat illustration of jobs on a conveyor heading to a rack of workers, with the JavaScript, Vite, Redis, Node.js and RabbitMQ logos.

The most common async bug in JavaScript produces no error. A function returns a promise, the caller forgets await, and the program carries on. If the promise succeeds, the work happens at some unknown time after the code that depended on it. If it rejects, the rejection has no handler and either crashes a Node.js process or disappears into a console warning in a browser. Reviewers miss it because the line looks normal. A linter does not, since a floating promise has a clear shape: an expression statement whose value is a promise that nobody uses. This post shows how to detect unawaited promises with @typescript-eslint/no-floating-promises and @typescript-eslint/no-misused-promises, how to set them up in a plain JavaScript project with type information, what each one reports and the idioms that fix the reports. It pairs with testing asynchronous code and handling errors without try/catch everywhere.

What a floating promise is

A floating promise is a promise created and then ignored: not awaited, not returned, not assigned and not given a .catch handler. These examples are all floating.

floating.jsJavaScript
async function save(user) {
  if (!user.name) throw new Error("name is required");
  return { saved: true };
}

function handleRequest(user) {
  save(user); // floating: errors vanish, order is not guaranteed
  console.log("response sent");
}

handleRequest({ name: "" });
Text
response sent

The response was sent and the validation error was never seen by the caller. In Node.js the rejected promise produces an unhandled rejection, which terminates a modern process with a stack trace after the line above has already printed. The cost of the bug is the gap between the symptom and its cause: the log says name is required with a stack that does not mention handleRequest.

Why plain ESLint cannot see it

A rule has to know which expressions are promises. ESLint alone works on syntax, so it sees save(user); and cannot tell whether save returns a promise. The typescript-eslint rules ask the TypeScript type checker, so they can. That means the rules need type information, which requires a TypeScript parser and a project configuration. The good news is that this works for JavaScript projects too: TypeScript can analyze .js files when allowJs and checkJs are enabled, or from JSDoc types, and inferred return types of async functions are enough for these rules.

Set it up

Install the packages and enable the parser's project service, which finds the right tsconfig.json for each file. With ESLint's flat configuration, the file looks like this.

eslint.config.jsJavaScript
import tseslint from "typescript-eslint";

export default tseslint.config(
  ...tseslint.configs.recommendedTypeChecked,
  {
    languageOptions: {
      parserOptions: {
        projectService: true,
        tsconfigRootDir: import.meta.dirname,
      },
    },
    rules: {
      "@typescript-eslint/no-floating-promises": "error",
      "@typescript-eslint/no-misused-promises": "error",
      "@typescript-eslint/await-thenable": "error",
    },
  }
);
tsconfig.jsonJSON
{
  "compilerOptions": {
    "allowJs": true,
    "checkJs": true,
    "noEmit": true,
    "module": "nodenext",
    "target": "es2023"
  },
  "include": ["src"]
}

The recommendedTypeChecked set already enables these rules, and the explicit lines make the intent visible. Running npx eslint src then reports the floating call:

Text
src/floating.js
  7:3  error  Promises must be awaited, end with a call to .catch, end with a call to .then with a rejection handler or be explicitly marked as ignored with the `void` operator  @typescript-eslint/no-floating-promises

āœ– 1 problem (1 error, 0 warnings)

The message lists the ways to resolve it, and each has a different meaning, as the next section shows. Type-aware linting is slower than syntax-only linting because it runs the type checker, so run it in continuous integration and in the editor, and keep the file list scoped to your source.

The four fixes and what each means

Await it. The usual fix: the caller waits for the result and receives the rejection.

await.jsJavaScript
async function save(user) {
  if (!user.name) throw new Error("name is required");
  return { saved: true };
}

async function handleRequest(user) {
  try {
    await save(user);
    console.log("response sent");
  } catch (error) {
    console.log("rejected:", error.message);
  }
}

await handleRequest({ name: "" });
Text
rejected: name is required

Return it. If the function's job is to hand the work to its caller, return the promise, and the caller takes over responsibility.

Handle it. When the work is meant to run on its own and must not block the caller, attach a handler that decides what failure means.

catch.jsJavaScript
const sendEmail = async () => {
  throw new Error("smtp down");
};

sendEmail().catch((error) => {
  console.log("email failed, will retry later:", error.message);
});
console.log("request finished without waiting for the email");
Text
request finished without waiting for the email
email failed, will retry later: smtp down

Mark it ignored with void. void sendEmail() tells the rule you meant to start the work and drop the result. Use it rarely, and only for operations where failure truly does not matter, since it also discards the error. Prefer the .catch form that logs.

no-misused-promises: promises in the wrong place

The second rule catches promises passed where a function that returns nothing is expected. Two common cases are conditions and callbacks.

misused.jsJavaScript
async function isAllowed() {
  return false;
}

if (isAllowed()) {
  console.log("allowed"); // always runs: a promise object is truthy
}
Text
allowed

The condition tests a promise, which is always truthy, so the check passes for everyone. no-misused-promises reports it under its checksConditionals option, which is on by default. The other case is an async function passed to something that ignores the returned promise, such as forEach or an event listener. With checksVoidReturn enabled, passing async () => {...} to array.forEach is reported, which catches the problem described in awaiting in a forEach loop. For event listeners, whose async handlers are common and legitimate, you can set checksVoidReturn: { attributes: false } to relax it for JSX attributes, and handle errors inside the handler.

await-thenable and the reverse bug

The third rule, await-thenable, reports await applied to something that is not a promise. It is a smaller bug, but it often points to a function that used to be async and no longer is, or to a missing async on a function that the caller expected to be one. Both signal a mismatch between what the author believed and what the code does.

Adopting the rules in an existing codebase

Turning on no-floating-promises in a large codebase can produce hundreds of errors. Fix them in stages. Start by enabling the rule as a warning, and use the report to find real bugs, since in practice a few percent of reports are genuine, and those are worth the whole exercise. Then fix by directory, and move the rule to an error once the count is zero, so new code cannot add to it. Resist the temptation to put void in front of every report to silence it, which hides exactly the bugs the rule exists to find.

Catching the rest at runtime

A linter sees the code, and a running process sees what actually happens. Register an unhandledRejection handler in Node.js that logs the reason and the stack and then exits with a non-zero code. That is already the default behavior since Node.js 15, so the point is to log in a form your monitoring picks up, and to make sure a process manager restarts the service. In browsers, listen for the unhandledrejection event on window and send the reason to your error tracker. These handlers turn the bugs the linter missed, for example promises hidden behind any types or dynamic calls, into visible errors with a stack trace instead of silent failures.

Tests are a second net. A test runner that fails the run on unhandled rejections catches a floating promise at the moment a test triggers it. Node's built-in runner reports an error when an unhandled rejection occurs during a test file, and Jest and Vitest have similar options. Keep that setting on, and treat a warning about an unhandled rejection in test output as a failure.

Making the habit stick

Rules alone do not change how a team writes code, and a few conventions help. Name functions that return promises so that a reader can tell: a fetchUser or a saveOrder suggests work that takes time, while a getName suggests a plain value. Prefer async functions to hand-built promise chains, since a forgotten await is easier to spot than a forgotten return inside a .then. When a function deliberately starts background work and returns nothing, give the start a name such as startSync and make it handle its own errors, so callers have nothing to await and nothing to leak. And when reviewing, look at every call to an async function and ask who receives its result and who receives its error.

What the rules do not catch

The lint rules work on types, so they are only as good as the types. A function typed as returning any, or a callback whose type loses the promise, hides the problem from them. Promises stored in an array and never awaited as a group, such as a map that creates promises and drops the array, are caught only in simple cases, and Promise.all on the array is the fix. Libraries that return thenables with unusual shapes may be missed. For those, code review and runtime handlers remain necessary, and the lint rules reduce the number of cases that reach them.

Also inTooling
Share

Keep reading

Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.