Async/Await — Explained with Examples
Async/await is syntactic sugar for working with promises or futures, allowing asynchronous code to be written in a sequential, readable style.
Async/await transforms asynchronous promise-based code into something resembling synchronous code. An async function returns a promise. The await keyword pauses the function until the promise resolves, without blocking the thread. Behind the scenes, the compiler transforms async/await into a state machine or coroutine. Languages supporting async/await include JavaScript, Python, C#, Rust, and Kotlin.
Think of async/await like a restaurant order system. A server takes your order (starts async operation), gives you a buzzer (promise), and continues serving other tables. When the buzzer lights up (promise resolves), the server picks up the food and delivers it (continues execution after await).
Before async/await, JavaScript used nested callbacks (callback hell) or promise chains. Async/await makes the code read top-to-bottom while remaining non-blocking.
// Without async/await — promise chain
function getData() {
return fetch('/api/user')
.then(response => response.json())
.then(user => fetch(`/api/posts/${user.id}`))
.then(response => response.json())
.catch(err => console.error(err));
}
// With async/await — sequential readability
async function getData() {
try {
const userResponse = await fetch('/api/user');
const user = await userResponse.json();
const postsResponse = await fetch(`/api/posts/${user.id}`);
return await postsResponse.json();
} catch (err) {
console.error(err);
}
}
// Parallel execution with async/await
async function getParallelData() {
const [users, posts] = await Promise.all([
fetch('/api/users').then(r => r.json()),
fetch('/api/posts').then(r => r.json()),
]);
return { users, posts };
}Async/await does not create new threads. It relies on an event loop or runtime scheduler to manage concurrency. Await only blocks within the async function, not the entire thread.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro