Using await inside a non-async function in JavaScript will result in a syntax error. This is because await is only valid within an async function or at the top level of a module (in modern JavaScript environments).
Common Error Example
function fetchData() {
const response = await fetch('https://api.example.com/data'); // ❌ Error here
const data = await response.json();
console.log(data);
}
Error:Uncaught SyntaxError: Unexpected token 'await'
How to Fix It
1. Declare the Function as async
async function fetchData() {
const response = await fetch('https://api.example.com/data'); // ✅ Works now
const data = await response.json();
console.log(data);
}
Now the function can use await without issues.
2. Use then() for Non-Async Functions
If you can’t make the function async, use Promises with .then():
function fetchData() {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
}
This avoids the need for await altogether.
3. Using async with an IIFE (Immediately Invoked Function Expression)
If you need to use await inside a non-async function, you can create an async IIFE:
function fetchData() {
(async () => {
try {
const response = await fetch('https://api.example.com/data');
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
})();
}
This allows await to work inside a regular function without changing its signature.
Key Takeaways
awaitrequires anasyncfunction.- Use
.then()ifasyncisn’t an option. - Use an
asyncIIFE if you needawaitinside a regular function.
