Using await inside a non-async function

Loading

Using await Inside a Non-async Function

Using the await keyword inside a function that is not declared as async will result in a syntax error in JavaScript. This is because await can only be used inside async functions or at the top level of modules (with ES2022 and newer).


Common Mistake Example (Syntax Error):

function fetchData() {
  const response = await fetch('https://api.example.com/data'); // ❌ Error: 'await' is only valid in async functions
  const data = await response.json();
  console.log(data);
}

fetchData();

Error Message:

SyntaxError: Unexpected reserved word 'await'

Why This Causes an Error:

  • await is used to pause the function until the Promise resolves, but the function isn’t marked as async.
  • JavaScript expects await to be inside an async function.

Correct Way (Declaring the Function as async):

async function fetchData() {
  const response = await fetch('https://api.example.com/data'); // ✅ Works because the function is async
  const data = await response.json();
  console.log(data);
}

fetchData();

Why This Works:

  • Declaring the function as async allows the use of await.
  • The function now handles the Promise correctly, pausing execution until the response is received.

Common Mistake: Mixing async with Non-async Code

function processData() {
  const data = await getData(); // ❌ Error: 'await' used without async
  console.log(data);
}

Fix:

async function processData() {
  const data = await getData(); // ✅ Correct
  console.log(data);
}

Using async with Arrow Functions

const fetchData = async () => {
  const response = await fetch('https://api.example.com/data');
  const data = await response.json();
  console.log(data);
};

fetchData();

Why This Works:

  • Arrow functions can also be declared as async.
  • This syntax is clean and widely used in modern JavaScript.

Mistake: Using await in Global Scope (Without Top-Level Await)

const data = await fetch('https://api.example.com/data'); // ❌ Error outside an async function
const json = await data.json();
console.log(json);

Fix (Using Top-Level await in Modules):

If you’re using an ES module (with "type": "module" in package.json), top-level await is allowed:

const data = await fetch('https://api.example.com/data'); // ✅ Works in ES module
const json = await data.json();
console.log(json);

Otherwise:

  • Wrap it inside an async function or use .then() for Promise chaining.

Key Takeaways:

  • await can only be used inside async functions or at the top level in ES modules (ES2022+).
  • Always declare the function with async if using await inside it.
  • Use try-catch blocks for error handling with await to manage network failures gracefully.

Leave a Reply

Your email address will not be published. Required fields are marked *