DEV Community

Cover image for A Deep Dive into .then() Method in JavaScript: How to Use it Like a Pro
Rahul Ladumor for TheTechGuruWorld

Posted on • Updated on

A Deep Dive into .then() Method in JavaScript: How to Use it Like a Pro

Learn How to Maximise the Power of .then and Boost Your JavaScript Coding

Do you have trouble with JavaScript's asynchronous programming? Do not look past the simple ".then" approach. Whether you're a novice JavaScript developer or a seasoned programmer, mastering.then can help you advance your code. In this post, we'll examine the potential of.then and offer practical examples of its use in order to streamline and improve your code.

πŸ‘‰πŸΌ Understanding .then

Let's start with the fundamentals first. JavaScript uses the.then method to handle a Promise's outcome. Promises are used to represent values like data obtained from a server or user input that may not yet be ready. You can manage the Promise's outcome in your code by calling the.then method when the Promise is resolved.

Here's an easy illustration:

fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(data => console.log(data))
Enter fullscreen mode Exit fullscreen mode

In this example, we're requesting a JSON object from an API using the fetch method. The response is transformed into a JSON object using the first .then method, and the data is logged to the console using the second .then method.

πŸ‘‰πŸΌ Chaining .then Methods

One of the most powerful features of .then is the ability to chain multiple methods together. This allows you to perform multiple actions on the result of a Promise without having to nest callbacks.

Here's sample example:

fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(data => {
    console.log(data);
    return data.userId;
  })
  .then(userId => console.log(`User ID: ${userId}`));
Enter fullscreen mode Exit fullscreen mode

In this example, we're using the first .then method to convert the response into a JSON object, and the second .then method to log the data and return the userId. The third .then method then logs the userId to the console.

.catch for handling errors

While.then is excellent for dealing with successful Promises, it's also crucial to deal with mistakes that could happen at any point in the Promise's lifespan. The.catch technique is useful in this situation.

Here's an Example code:

fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));
Enter fullscreen mode Exit fullscreen mode

In this Example we're utilising the.catch method to deal with any issues that might come up while the Promise is in use. An error will be recorded to the console if it happens.

πŸ‘‰πŸΌ Let's see the real-world Example

Let's look at some actual examples to see how you may use.then to organise and streamline your code.

Scenario 1: Handling Multiple Promises

Promise.all([fetch('https://jsonplaceholder.typicode.com/todos/1'), fetch('https://jsonplaceholder.typicode.com/todos/2')])
  .then(responses => Promise.all(responses.map(response => response.json())))
  .then(data => console.log(data))
  .catch(error => console.error(error));
Enter fullscreen mode Exit fullscreen mode

In this example, we're using Promise.all to fetch data from two different API endpoints. We're then using the .then method to convert the responses into JSON objects and log the data to the console.

Scenario 2: Performing Multiple Actions on the Same Promise

fetch("https://jsonplaceholder.typicode.com/todos/1")
  .then((response) => response.json())
  .then((data) => {
    console.log(data);
    data.completed = true;
    return fetch("https://jsonplaceholder.typicode.com/todos/1", {
      method: "PUT",
      body: JSON.stringify(data),
      headers: {
        "Content-Type": "application/json",
      },
    });
  })
  .then((response) => response.json())
  .then((updatedData) => console.log(updatedData))
  .catch((error) => console.error(error));
Enter fullscreen mode Exit fullscreen mode

In this example, we're using the first .then method to convert the response into a JSON object and set the completed property to true. We're then using the second .then method to make a PUT request to update the data on the API, and the third .then method to log the updated data to the console.

πŸ‘‰πŸΌ Conclusion

In conclusion, .then is a powerful method in JavaScript that can simplify and streamline your code when working with Promises. By understanding how to chain .then methods and handle errors with .catch, you can take full advantage of the asynchronous nature of JavaScript and create more efficient and effective code.

As the JavaScript developer and author Addy Osmani once said,

Promises allow us to write async code as if it were sync, and with .then, we can do it in a way that's easy to read and maintain.

Illustration of a developer, with Indian descent, diving into a sea of code. The sea is filled with JavaScript symbols and functions. Prominently in the middle, there's a giant chain with links labeled '.then()'. The background shows a digital matrix, symbolizing the intricate world of JavaScript, and the developer is equipped with tools that signify mastery and expertise.

Thank you for reading and happy coding! 😊

Top comments (2)

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 πŸ‘

Collapse
 
rahulladumor profile image
Rahul Ladumor

Thanks πŸ‘