JavaScript Promises and Async/Await Explained
JavaScript • Concepts Explained • 7 min read
Asynchronous JavaScript confuses many beginners. This article breaks down Promises and async/await with clear examples.
JavaScript Promises and Async/Await Explained
Asynchronous code is everywhere in JavaScript. API calls, file reading, timers — they all happen asynchronously. Promises and async/await make this manageable.
The Problem: Callback Hell
Before promises, we used callbacks, leading to nested, hard-to-read code:
// Callback hell
getUser(userId, function(user) {
getOrders(user.id, function(orders) {
getOrderDetails(orders[0].id, function(details) {
console.log(details);
});
});
});
Promises: A Better Way
A Promise represents a value that will be available later. It can succeed or fail:
// Creating a promise
function getUser(id) {
return new Promise((resolve, reject) => {
if (id > 0) {
resolve({ id: id, name: 'John' });
} else {
reject(new Error('Invalid ID'));
}
});
}
// Using a promise
getUser(1)
.then(user => console.log(user))
.catch(error => console.error(error));
Chaining Promises
getUser(1)
.then(user => getOrders(user.id))
.then(orders => getOrderDetails(orders[0].id))
.then(details => console.log(details))
.catch(error => console.error(error));
Async/Await: Even Cleaner
Async/await makes asynchronous code look synchronous:
async function getUserDetails(userId) {
try {
const user = await getUser(userId);
const orders = await getOrders(user.id);
const details = await getOrderDetails(orders[0].id);
return details;
} catch (error) {
console.error(error);
}
}
getUserDetails(1).then(details => console.log(details));
Key Rules
awaitcan only be used insideasyncfunctionsasyncfunctions always return a promise- Use
try/catchto handle errors with async/await Promise.all()runs multiple promises in parallel
// Run multiple requests in parallel
const [users, posts, comments] = await Promise.all([
fetchUsers(),
fetchPosts(),
fetchComments()
]);
Note: Use async/await for most cases. It's cleaner and easier to debug. Reserve raw promises for complex parallel operations.