← Back to Node.js Course | Chapter 4: Async Programming | Lesson 2 of 7

Promises

A promise stands for a value that will exist later: it can be pending, fulfilled or rejected.

In this page:

  1. Promises
Syntax
javascript
promise
  .then((result) => {
    // success
  })
  .catch((err) => {
    // failure
  })
  .finally(() => {
    // always runs
  });

Promises

A promise's then handles success, catch handles failure and finally runs either way. Handlers return new promises so you can chain them. Creating promises with new Promise wraps callback APIs.

Note: Always end chains with a catch so rejections are not unhandled.

Example: Promises

javascript
const p = new Promise((resolve, reject) => {
  setTimeout(() => resolve(21), 5);
});
p.then((n) => n * 2)
  .then((n) => { console.log("result:", n); throw new Error("oops"); })
  .catch((e) => console.log("caught:", e.message))
  .finally(() => console.log("cleanup"));

// Output:
// result: 42
// caught: oops
// cleanup

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
Common Mistakes
  1. Forgetting to return inside then
  2. Leaving rejections unhandled
  3. Creating a promise inside a promise unnecessarily
Chapter Summary
  • States: pending, fulfilled, rejected
  • then, catch and finally handle results
  • Chains return new promises
  • Always add catch
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.