Promises & async/await
Master JavaScript Promises and the async/await syntax for clean, readable asynchronous Node.js code, including Promise.all and error handling.
Master JavaScript Promises and the async/await syntax for clean, readable asynchronous Node.js code, including Promise.all and error handling.
Here's everything this chapter covers, in the order you'll learn it:
- What a Promise is
- The three states: pending, fulfilled, rejected
- .then() for handling success
- .catch() for handling errors
- .finally() for cleanup code
- Promise chaining
- The async keyword
- The await keyword
- Error handling with try/catch inside async functions
- Promise.all() for running tasks in parallel
- Promise.allSettled()
- Promise.race()
- Sequential vs parallel async tasks
async function loadData() {
try {
const data = await Promise.resolve("Data received");
console.log(data);
} catch (error) {
console.error(error.message);
}
}
loadData();
// Running multiple async tasks in PARALLEL, not one-by-one
const [users, posts] = await Promise.all([
fetchUsers(),
fetchPosts(),
]);
- Always wrap await calls in try/catch inside async functions โ an unhandled rejection can crash a Node.js process.
- Use Promise.all() when tasks don't depend on each other, to run them concurrently instead of sequentially (much faster).
Q What's the most important thing to understand about promises & async/await?
Focus on: Promise States ยท .then/.catch/.finally ยท async/await ยท Promise.all() ยท Promise.race(). These are the core building blocks this chapter's examples are built around, and they show up repeatedly in later chapters of this course.
Q Do I need external npm packages for promises & async/await?
Only where explicitly shown in the code examples above (like Express, Zod, or Socket.IO) โ otherwise, this chapter relies entirely on Node.js's own built-in capabilities.