Topic 85 of 87
Async / Await
Overview
Introduced in ES8 (2017), async/await is modern "syntactic sugar" built directly on top of Promises.
It allows you to write asynchronous code that looks and behaves like synchronous code. Instead of chaining .then() blocks, you simply put the word await in front of a Promise, and the JavaScript engine will pause the function's execution until that Promise resolves.
Syntax
The Clean Syntax
javascript
// You MUST mark the function as 'async'
async function getUserData() {
try {
// Execution pauses here until fetch finishes
const response = await fetch('https://api.github.com/users');
// Execution pauses here until json parsing finishes
const data = await response.json();
console.log(data);
} catch (error) {
// Errors are caught cleanly with try/catch!
console.error("Fetch failed:", error);
}
}Common Pitfalls
- Using
awaitinside a standard.forEach()loop. The loop will fire off all iterations concurrently without waiting! If you need to await operations sequentially in a loop, you MUST use afor...ofloop or a standardforloop. - Forgetting the
asynckeyword. You cannot use the wordawaitinside a normal function. The function must be explicitly declared asasync functionorconst fn = async () => {}.
Interview Questions
Q:
What does an
async function implicitly return?A:
An async function ALWAYS returns a Promise, even if you explicitly return a primitive value like return 5;. JavaScript will automatically wrap that 5 in a resolved Promise: Promise.resolve(5).
Real-World Example
A complete, modern React data fetching pattern inside a useEffect.
example
javascript
useEffect(() => {
async function loadData() {
const res = await api.get('/profile');
setProfile(res.data);
}
loadData();
}, []);Check Your Knowledge
Test your understanding of Async / Await with these quick questions.