Await Expressions Can Be Used Anywhere
You'll learn that await isn't limited to standalone statements—it's a flexible expression you can use wherever JavaScript expects a value.
The Core Idea
In earlier lessons, you saw await used at the start of lines, like const result = await somePromise(). But await is an expression, not just a statement. That means it produces a value and can be used in any position where JavaScript expects an expression: inside function calls, conditionals, arithmetic operations, template literals, or anywhere else.
Think of await like parentheses in math: just as you can write (2 + 3) anywhere you'd use 5, you can use await promise anywhere you'd use the value that promise resolves to.
Common Expression Positions
In function arguments:
async function greet() {
console.log(await fetchName(), await fetchGreeting());
}
In conditionals:
async function checkAccess() {
if (await isUserAdmin()) {
console.log("Admin access granted");
}
}
In assignments with operations:
async function calculate() {
const total = (await getPrice()) * (await getQuantity());
return total;
}
In template literals:
async function buildMessage() {
const msg = `Hello, ${await fetchUsername()}!`;
return msg;
}
In return statements:
async function getData() {
return await fetchData(); // Though usually redundant
}
The key is recognizing that await resolves to a value, so it fits naturally wherever that value would go.
Key Takeaway: Await expressions can appear in any valid expression position—function arguments, conditionals, calculations, or template literals—making async code read almost like synchronous code.