DEV Community

Cover image for What are JavaScript Promises? Explain with practical Examples
Rahul Bagal
Rahul Bagal

Posted on • Updated on

What are JavaScript Promises? Explain with practical Examples

What are JavaScript Promises? An Introduction

As a WordPress developer, it's crucial to understand the basics of JavaScript, a popular programming language used to create interactive web applications. One concept that is essential to learn is JavaScript Promises. In this article, we'll dive into what JavaScript Promises are, how they work, and provide practical examples of how they can be used in your WordPress development projects.

Understanding JavaScript Promises

A Promise in JavaScript is an object representing the eventual completion or failure of an asynchronous operation. In simpler terms, a Promise is a way to handle asynchronous operations like fetching data or making API calls, where the result may not be immediately available.

A Promise can be in one of three states:

  1. Pending: The initial state, neither fulfilled nor rejected.

  2. Fulfilled: The operation completed successfully, and the Promise has a resulting value.

  3. Rejected: The operation failed, and the Promise has a reason for the failure.

How Do Promises Work?

Promises have two main methods, .then() and .catch(). The .then() method is called when the Promise is fulfilled, while the .catch() method is called when the Promise is rejected.

Here's an example:

javascriptCopy codeconst fetchData = new Promise((resolve, reject) => {
  // Simulate a delay of 2 seconds
  setTimeout(() => {
    const data = { name: "John Doe", age: 30 };
    resolve(data);
  }, 2000);
});

fetchData.then((data) => {
  console.log(data); // { name: "John Doe", age: 30 }
}).catch((error) => {
  console.log(error);
});
Enter fullscreen mode Exit fullscreen mode

In the example above, we create a new Promise called fetchData. We use the setTimeout() function to simulate a delay of 2 seconds, then resolve the Promise with some data.

We then use the .then() method to log the data to the console when the Promise is fulfilled, and the .catch() method to log any errors that may occur.

Practical Examples

Now that we understand the basics of Promises, let's explore some practical examples of how they can be used in WordPress development.

Fetching Data from an API

javascriptCopy codeconst fetchPosts = fetch('https://jsonplaceholder.typicode.com/posts');

fetchPosts
  .then((response) => response.json())
  .then((data) => {
    // Do something with the data
  })
  .catch((error) => {
    console.log(error);
  });
Enter fullscreen mode Exit fullscreen mode

In this example, we're using the fetch() method to fetch data from a JSON API. We then use the .then() method to parse the response into JSON format, and another .then() method to handle the data once it's available.

Handling Multiple Promises with Promise.all()

javascriptCopy codeconst fetchPosts = fetch('https://jsonplaceholder.typicode.com/posts');
const fetchComments = fetch('https://jsonplaceholder.typicode.com/comments');

Promise.all([fetchPosts, fetchComments])
  .then((responses) => {
    const [postsResponse, commentsResponse] = responses;
    return Promise.all([postsResponse.json(), commentsResponse.json()]);
  })
  .then((data) => {
    const [posts, comments] = data;
    // Do something with the data
  })
  .catch((error) => {
    console.log(error);
  });
Enter fullscreen mode Exit fullscreen mode

In this example, we're using the Promise.all() method to handle multiple Promises at once. We create two Promises using the fetch() method, and then pass them to Promise.all().

The .then() method is called when both Promises have One important feature of promises is the ability to chain them. Chaining promises means that one promise is executed after another, and the result of the first promise is passed as a parameter to the second promise. This is useful when you have multiple asynchronous operations that depend on each other.

For example, let's say we have a website that displays a list of user posts. Each post has a title and a body, and we want to display the title and the first 100 characters of the body. We can make a request to the server to get the list of posts, and then make another request for each post to get the body. With promises, we can chain these two requests like this:

javascriptCopy codefetch('/posts')
  .then(response => response.json())
  .then(posts => {
    const postPromises = posts.map(post => {
      return fetch(`/posts/${post.id}`)
        .then(response => response.json())
        .then(data => {
          post.body = data.body.substring(0, 100);
          return post;
        });
    });
    return Promise.all(postPromises);
  })
  .then(posts => {
    // display the posts on the page
  })
  .catch(error => {
    console.error(error);
  });
Enter fullscreen mode Exit fullscreen mode

In this example, we first make a request to the server to get the list of posts. We use the fetch API to make the request and receive a response. We then call the json() method on the response to parse the JSON data. This returns another promise, which we chain to the first promise using the then() method.

The second promise returns an array of promises, one for each post. We use the map() method to iterate over the list of posts and create a new promise for each post. We make another request to the server to get the body of the post, and use the substring() method to get the first 100 characters of the body. We then update the post object with the shortened body and return it.

We use the Promise.all() method to wait for all of the promises in the array to resolve. This method returns a new promise that resolves with an array of the resolved values of all the promises. We chain this promise to the previous promise using the then() method.

Finally, we have an array of posts with the shortened bodies. We can display these on the page as desired.

In conclusion, JavaScript promises are a powerful tool for working with asynchronous code. They make it easy to handle complex chains of asynchronous operations and provide a more readable and maintainable code structure. With practical examples like the one above, you can begin to see how promises can be used to simplify your code and improve its functionality.

Top comments (1)

Collapse
 
fruntend profile image
fruntend

Сongratulations 🥳! Your article hit the top posts for the week - dev.to/fruntend/top-10-posts-for-f...
Keep it up 👍