await and arrow functions
1. await only works inside async functions
await is an operator that can be used only inside a function declared with the async keyword,
or at the top level of a module (top-level await).
If you use await outside async, you get a syntax error:
// Error
const result = await Promise.resolve(42);
// SyntaxError: await is only valid in async functions2. Correct syntax with an arrow function
To use await, you need to make the arrow function asynchronous:
const fetchData = async () => {
const data = await Promise.resolve('Done');
console.log(data);
};
fetchData();Result:
Doneasync before an arrow function turns it into an asynchronous function,
which always returns a promise.
3. If you omit async, await won't work
const foo = () => {
const data = await Promise.resolve('Error');
console.log(data);
};
// SyntaxError: await is only valid in async functionsWithout async, this is simply a syntax error.
JS won't even run the code, because await is not allowed in a regular function.
4. Return value
An async arrow function always returns a promise,
even if it contains no await at all.
const sum = async (a, b) => a + b;
console.log(sum(1, 2)); // Promise { 3 }This is the same as:
function sum(a, b) {
return Promise.resolve(a + b);
}5. Examples of different forms
A regular arrow function with await:
const loadUser = async () => {
const res = await fetch('/api/user');
return res.json();
};With parameters:
const getUser = async (id) => {
const res = await fetch(`/api/user/${id}`);
return res.json();
};Multi-line form:
const processData = async () => {
const data = await fetch('/api/data');
const json = await data.json();
console.log(json);
};In a promise chain:
Promise.resolve('A')
.then(async (x) => {
const y = await Promise.resolve('B');
return x + y;
})
.then(console.log); // "AB"Here then() accepts an async arrow function,
and await inside it is fully legal.
6. Top-level await
Modern JS modules (ESM) allow await to be used outside functions,
as long as the code is in a module (not a <script> without type="module"):
// main.js
const data = await fetch('/api/data').then(r => r.json());
console.log(data);This is top-level await, it only works in ESM (or in Node.js with "type": "module").
A simple analogy
asyncbefore an arrow function is like a passport that grants permission to useawaitinside it.Without it,
awaitsimply doesn't know where to return the result.
SUMMARY
| Question | Answer |
|---|---|
Can you use await in an arrow function? | Yes, if it is declared as async |
What if there's no async? | SyntaxError: await is only valid in async functions |
What does an async arrow function return? | Always a Promise |
Can you await in .then() or callbacks? | Yes, if the callback is async |
Can you await outside a function? | Only with top-level await in modules |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.