JavaScript - Promises & Async/Await

Overview

Estimated time: 20–30 minutes

Promises and async/await make asynchronous code easier to write and read. Learn how to create, chain, and handle errors with promises, and how async/await simplifies async code.

Learning Objectives

  • Create and use promises.
  • Chain promises and handle errors.
  • Use async/await for cleaner async code.

Prerequisites

Creating Promises

const p = new Promise((resolve, reject) => {
  setTimeout(() => resolve('Done!'), 1000);
});

Chaining and Error Handling

p.then(result => {
  console.log(result);
  return 'Next';
}).then(next => {
  console.log(next);
}).catch(err => {
  console.error('Error:', err);
});

Async/Await

async function run() {
  try {
    const result = await p;
    console.log(result);
  } catch (e) {
    console.error('Error:', e);
  }
}
run();

Common Pitfalls

  • Forgetting to return or await a promise in a chain.
  • Uncaught promise rejections can crash Node.js (use .catch or try/catch).

Summary

Promises and async/await are the foundation of modern async JavaScript. Use them to write readable, robust code.