JS Promise Methods 🚀

beginner
10 min

JS Promise Methods 🚀

Welcome to our deep dive into JavaScript Promises! In this lesson, we'll learn about Promises, their importance, and various Promise methods that will help you write cleaner, more manageable asynchronous code. Let's get started!

What are Promises? 💡

Promises are a JavaScript object representing the eventual completion or failure of an asynchronous operation. They provide a way to handle asynchronous operations in a more organized and manageable manner.

javascript
// Example of a Promise const promise = new Promise((resolve, reject) => { // asynchronous operation setTimeout(() => { if (true) { resolve('Result'); } else { reject('Error'); } }, 2000); });

Understanding Promise States 📝

A Promise can be in one of three states:

  1. Pending (when it's created): neither resolved nor rejected.
  2. Resolved: when the asynchronous operation completes successfully and the resolve function is called.
  3. Rejected: when the asynchronous operation fails and the reject function is called.

The Importance of Promises ✅

Promises are essential for handling asynchronous operations in JavaScript. They allow for:

  • Better error handling: Promises help catch errors that occur during asynchronous operations and provide a structured way to handle them.
  • Improved readability: Promises make asynchronous code easier to understand and manage, making it more maintainable.
  • Avoiding callback hell: Promises help avoid the complex and hard-to-read callback chains commonly known as "callback hell."

Basic Promise Methods 🎯

.then()

The .then() method is used to specify what will happen when a Promise is resolved.

javascript
const promise = new Promise((resolve, reject) => { setTimeout(() => resolve('Result'), 2000); }); promise.then(result => { console.log(result); // logs 'Result' after 2 seconds });

.catch()

The .catch() method is used to specify what will happen when a Promise is rejected.

javascript
const promise = new Promise((resolve, reject) => { setTimeout(() => reject('Error'), 2000); }); promise.catch(error => { console.log(error); // logs 'Error' after 2 seconds });

Advanced Promise Methods

.all()

The .all() method is used to wait for multiple Promises to complete. It returns a new Promise that resolves when all of the input Promises are resolved or rejects if any of them are rejected.

javascript
const promise1 = new Promise((resolve, reject) => { setTimeout(() => resolve('Promise 1'), 1000); }); const promise2 = new Promise((resolve, reject) => { setTimeout(() => resolve('Promise 2'), 2000); }); Promise.all([promise1, promise2]).then(results => { console.log(results); // logs ['Promise 1', 'Promise 2'] });

.race()

The .race() method is used to wait for the first of multiple Promises to resolve or reject. It returns a new Promise that resolves or rejects with the result or reason from the first fulfilling Promise.

javascript
const promise1 = new Promise((resolve, reject) => { setTimeout(() => resolve('Promise 1'), 1000); }); const promise2 = new Promise((resolve, reject) => { setTimeout(() => reject('Error'), 2000); }); Promise.race([promise1, promise2]).then(result => { console.log(result); // logs 'Promise 1' after 1 second }).catch(error => { console.log(error); // not executed in this example });

Putting it all Together 📝

Promises can be used in a variety of applications, from fetching data from APIs to handling user interactions. Here's an example of using Promises to fetch data from an API and display it on a webpage:

javascript
const fetchData = (url) => { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.onload = () => { if (xhr.status === 200) { resolve(JSON.parse(xhr.responseText)); } else { reject(`Error: ${xhr.status}`); } }; xhr.onerror = () => reject('Network error'); xhr.send(); }); }; fetchData('https://api.example.com/data') .then(data => { // do something with the data console.log(data); }) .catch(error => { // handle the error console.log(error); });

Quiz Time 🎯

Quick Quiz
Question 1 of 1

What does the `.then()` method do in a JavaScript Promise?

Wrap Up 🎯

By now, you should have a good understanding of what JavaScript Promises are and how to use basic and advanced Promise methods. In our next lesson, we'll dive deeper into async/await, another powerful tool for handling asynchronous operations in JavaScript. Until then, keep practicing and happy coding! 😊