async/await for asynchronous requests
1. What is a Promise
A Promise is an object that represents the result of an asynchronous operation, which can end up:
- succeeding (
fulfilled) -> returning a value - failing (
rejected) - or being in progress (
pending)
Example with Promise:
function getData() {
return new Promise((resolve, reject) => {
setTimeout(() => resolve('Data received'), 1000);
});
}
getData().then(result => console.log(result)); // "Data received"Here we manually create a promise and handle the result via
.then().
2. What async/await does
asyncturns a function into a function that always returns a promise.awaitpauses code execution until the promise settles.
Example with async/await:
async function getData() {
const result = await new Promise(resolve => {
setTimeout(() => resolve('Data received'), 1000);
});
console.log(result);
}
getData(); // "Data received"The code becomes simpler, more readable, and looks almost synchronous. But under the hood, it's still the same promises.
Example 2. Comparing Promise vs async/await
Promise chain:
fetch('https://api.example.com/user')
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err));async/await:
async function loadUser() {
try {
const res = await fetch('https://api.example.com/user');
const data = await res.json();
console.log(data);
} catch (err) {
console.error(err);
}
}
loadUser();Same thing, but without the "
.then()ladder", it reads like ordinary sequential code.
3. Key features of async/await
Simplifies reading the code
Asynchronous operations can be written in logical order, rather than as nested .then() calls.
Works only inside an async function
await fetch('...'); // Error - await can only be used inside an async functionExample 3. Using it with several promises
async function getData() {
const user = await fetch('/user').then(r => r.json());
const posts = await fetch('/posts').then(r => r.json());
console.log(user, posts);
}Here the second request runs only after the first one, which is sometimes inefficient.
If the requests do not depend on each other, run them in parallel:
async function getData() {
const [user, posts] = await Promise.all([
fetch('/user').then(r => r.json()),
fetch('/posts').then(r => r.json())
]);
console.log(user, posts);
}
Promise.all()lets you run several asynchronous operations at the same time.
4. Error handling
Via try...catch (recommended):
async function getData() {
try {
const res = await fetch('https://wrong-url');
const data = await res.json();
console.log(data);
} catch (err) {
console.error('Request error:', err);
}
}Via .catch() (less convenient):
getData().catch(err => console.error(err));5. Returning a value from an async function
async function sum(a, b) {
return a + b;
}
const result = sum(2, 3);
console.log(result); // Promise { 5 }
asyncalways returns a Promise, even if you explicitly return a plain value.
To get the result:
sum(2, 3).then(console.log); // 5or
const result = await sum(2, 3);
console.log(result); // 56. Differences between async/await and Promise.then
| Criterion | Promise / .then() | async/await |
|---|---|---|
| Syntax | .then() chains | Sequential, like synchronous code |
| Error handling | .catch() | try...catch |
| Readability | Sometimes hard due to nesting | Very high |
| Parallel execution | Promise.all() | Same |
| Return value | Implicit via .then() | Via return inside an async function |
| Function type | Regular | Always returns a Promise |
Example 4. Visual comparison
Promise chain:
getUser()
.then(user => getPosts(user.id))
.then(posts => getComments(posts[0].id))
.then(comments => console.log(comments))
.catch(err => console.error(err));async/await:
async function loadComments() {
try {
const user = await getUser();
const posts = await getPosts(user.id);
const comments = await getComments(posts[0].id);
console.log(comments);
} catch (err) {
console.error(err);
}
}async/await makes asynchronous logic step by step and predictable, especially when you need to handle an error at any stage.
In short:
async/awaitis "syntactic sugar" overPromisethat lets you write asynchronous code as if it were synchronous, while under the hood the same promises are still at work.
A formula to remember:
async -> the function returns a Promise
await -> "wait until the Promise settles"
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.