async / await is syntactic sugar over Promises, making asynchronous code look synchronous. Under the hood, it still uses Promises, but handles them more cleanly.
1️⃣ async Function
- Declaring a function as
asyncautomatically returns a Promise. - If the function returns a value, it resolves the Promise.
- If the function throws an error, it rejects the Promise.
async function foo() {
return 42;
}
foo().then(console.log); // 42
Under the hood:
function foo() {
return Promise.resolve(42);
}
2️⃣ await Keyword
awaitpauses execution inside anasyncfunction until the Promise resolves or rejects.- It unwraps the value from the Promise automatically.
- If the Promise rejects, it throws an exception that can be caught with
try/catch.
async function fetchData() {
const result = await fetch("https://api.example.com/data");
const data = await result.json();
console.log(data);
}
Under the hood:
function fetchData() {
return fetch("https://api.example.com/data")
.then(result => result.json())
.then(data => console.log(data));
}
3️⃣ Error Handling
With await, try/catch is used instead of .catch():
async function getData() {
try {
const data = await fetchData();
console.log(data);
} catch (err) {
console.error("Error:", err);
}
}
Under the hood, it’s still Promise chaining with .then() and .catch().
4️⃣ Execution Flow
asyncfunction is called → returns a Promise immediately.- When
awaitencounters a Promise → JS pauses execution of that async function but does not block the main thread. - Once the Promise settles → execution resumes from the
awaitline.
flowchart LR
A[Call async function] --> B[Returns a Promise]
B --> C[Pause at await for Promise]
C --> D[Promise resolves/rejects]
D --> E[Resume execution of function]
⚡ In short:
async/awaitwraps Promises and lets you write asynchronous code in a synchronous style. It pauses function execution atawaitwithout blocking the event loop, then resumes when the Promise resolves or rejects.
It’s purely syntactic sugar over Promises — nothing magically changes the async behavior of JavaScript.