![]()
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:
awaitis used to pause the function until thePromiseresolves, but the function isn’t marked asasync.- JavaScript expects
awaitto be inside anasyncfunction.
✅ 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
asyncallows the use ofawait. - The function now handles the
Promisecorrectly, 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
asyncfunction or use.then()for Promise chaining.
Key Takeaways:
awaitcan only be used insideasyncfunctions or at the top level in ES modules (ES2022+).- Always declare the function with
asyncif usingawaitinside it. - Use
try-catchblocks for error handling withawaitto manage network failures gracefully.
