Async Function Syntax
What you'll learn: How to write async functions using all four syntactic forms in JavaScript.
The Four Ways to Write Async Functions
Just like regular functions in JavaScript, async functions can be written in multiple syntactic forms. The async keyword can be applied to function declarations, function expressions, arrow functions, and object methods. Each form works identically—they all create functions that return promises automatically—but the syntax varies to fit different coding contexts.
Think of async as a label you can stick onto any function format you're already familiar with. It's like a "superpower badge" that transforms any function into one that handles asynchronous operations smoothly.
Function Declaration
async function fetchUser() {
// Returns a promise automatically
return { name: 'Alice' };
}
Function Expression
const fetchUser = async function() {
return { name: 'Alice' };
};
Arrow Function
const fetchUser = async () => {
return { name: 'Alice' };
};
Object Method
const api = {
async fetchUser() {
return { name: 'Alice' };
}
};
Which One Should You Use?
Choose based on your coding context:
- Declaration: When you need hoisting or clear top-level functions
- Expression: For passing callbacks or storing in variables
- Arrow: For concise inline callbacks (like in
.then()chains) - Method: When defining async operations inside objects or classes
All four forms automatically wrap their return values in promises and allow you to use await inside them (which you'll learn about next).
Key Takeaway: The async keyword can be added to any function syntax—declarations, expressions, arrows, or methods—giving you flexibility to write asynchronous code in whatever style fits your situation best.