JS Learning

Asynchronous Programming

Lesson Progress0%

Promises

Topic Overview

Take your time to understand each concept. Practice with the examples below!

A Promise is like a receipt for something that will happen in the future. When you order online, you get a tracking number (promise) - the package will either arrive (fulfilled) or get lost (rejected).

Promise States:

1. Pending - Still waiting for result 2. Fulfilled - Success! Got the result 3. Rejected - Failed, something went wrong

Creating a Promise:

const myPromise = new Promise((resolve, reject) => {
// Async operation here
if (everythingWentWell) {
resolve("Success!"); // Promise fulfilled
} else {
reject("Error!"); // Promise rejected
}
});

Using Promises:

  • .then() - Runs if promise succeeds
  • .catch() - Runs if promise fails
  • .finally() - Always runs at the end
myPromise
.then(result => {
console.log("Success:", result);
})
.catch(error => {
console.log("Failed:", error);
})
.finally(() => {
console.log("All done!");
});

Chaining Promises (solving callback hell):

fetchUser() .then(user => fetchPosts(user.id)) .then(posts => displayPosts(posts)) .catch(error => showError(error));

Why Promises are better than callbacks:

  • Cleaner, more readable code
  • Better error handling
  • Can chain operations easily
  • Avoid deeply nested callbacks

Ready to practice? Try the exercise below to reinforce your learning!

Try it yourself

Create a Promise that resolves with a random number after 1 second, or rejects if the number is less than 0.5.

Loading...