Course contentsShow
← JavaScript
Lesson 1343 of 2,72330. Async/AwaitFree lesson

Await Only Works in Async Functions

Using await outside an async function throws a SyntaxError; it requires the async context to function.

Await Only Works in Async Functions

You'll learn why await requires the async keyword and what happens if you forget it.

The Async Context Rule

The await keyword has a strict requirement: it can only be used inside functions marked with the async keyword. If you try to use await at the top level of a regular script or inside a non-async function, JavaScript will throw a SyntaxError before your code even runs.

Think of it like a special tool that only works in a designated workspace. You can't use await just anywhere—it needs the proper environment (an async function) to operate.

Why This Error Happens

// ❌ SyntaxError: await is only valid in async functions
function fetchData() {
  const result = await fetch('https://api.example.com/data');
  return result;
}

// ✅ Correct: function is marked async
async function fetchData() {
  const result = await fetch('https://api.example.com/data');
  return result;
}

The async keyword tells JavaScript to transform the function into one that can pause and resume execution. Without that transformation, await has nowhere to "pause" to—the function isn't equipped to handle it.

Common Mistake

// ❌ Won't work - top-level await in regular scripts
const data = await fetchData();

// ✅ Wrap in an async function
(async () => {
  const data = await fetchData();
  console.log(data);
})();

Even at the top level, you need an async wrapper function unless you're using ES modules with top-level await support (which we haven't covered yet).

Key Takeaway: await is inseparable from async—always mark your function with async before using await inside it, or JavaScript will reject your code with a SyntaxError.