Skip to content

'await' is only allowed in async functions

Error message

                'await' is only allowed within async functions
              

Quick summary

You used the `await` keyword outside of an async function or at the top level without top-level await support. await requires an async context.

Why this happens

  • Using await in a non-async function

  • Using await at the top level without ESM module support

  • Forgetting to add async to a function that uses await

  • Using await in a callback that isn't async

Minimal example

✗ Broken code
function fetchData() {
  const data = await fetch("/api"); // not in async function
}
✓ Fixed code
async function fetchData() {
  const data = await fetch("/api");
}

Add the async keyword to the function declaration.

How to diagnose

  • Check if the enclosing function is declared with async

  • Check if you're at the top level (needs ESM + top-level await)

  • Look for callbacks that need to be async

How to fix

  • Add async to the enclosing function: async function foo()

  • Use .then() instead of await for non-async callbacks

  • Enable top-level await in tsconfig (module: ESNext, target: ES2022)

  • Wrap the code in an async IIFE: (async () => { await ... })()

How to prevent

  • Always add async when using await in a function

  • Use ESLint with require-await rule

← Back to language