Async Functions
Async Functions
Section titled “Async Functions”Introduction
Section titled “Introduction”An async function is a function that always returns a Promise. It allows you to use the await keyword inside it.
Basic Syntax
Section titled “Basic Syntax”// An async function always returns a Promiseasync function getData() { return 'Hello';}
console.log(getData()); // Promise { 'Hello' }getData().then(console.log); // 'Hello'Arrow Functions
Section titled “Arrow Functions”const getData = async () => { return 'Hello';};
// With paramsconst fetchUser = async (id) => { const response = await fetch(`/api/users/${id}`); return response.json();};Visual Explanation
Section titled “Visual Explanation”flowchart TD A["async function fetchData()"] B["await fetch('/api/data')"] C["⏳ Pauses here until Promise resolves"] D["Continues with result"] E["Returns a Promise automatically"]
A --> B B --> C C --> D D --> ESummary
Section titled “Summary”asynckeyword makes a function return a Promise- Works with function declarations, expressions, and arrow functions
- Inside an async function, you can use
await - The returned value is automatically wrapped in a resolved Promise