What is the use of the then() method in JavaScript Promises?

Promises are an essential part of modern JavaScript development, providing a mechanism for managing asynchronous operations.

A promise is an object that represents a value that may not be available yet but will be resolved at some point in the future, either with a successful value or an error.

In JavaScript, the Promise constructor takes a function as its argument, which defines the asynchronous operation. This function, called the executor function, takes two parameters: resolve and reject. When the operation is successful, the resolve function is called with the result value, and when it fails, the reject function is called with an error object.

const myPromise = new Promise((resolve, reject) => {
  // Asynchronous operation
  // ...
  if (/* operation successful */) {
    resolve(result);
  } else {
    reject(error);
  }
});

Once a promise is created, it can be chained with other promises using the then() method. The then() method takes two arguments: a success callback function and an error callback function. The success callback function is called when the promise is resolved successfully, and the error callback function is called when the promise is rejected.

myPromise
  .then((result) => {
    // handle successful result
  })
  .catch((error) => {
    // handle error
  });

The then() method returns a new promise, which can be chained with further promises using the then() method. This allows for a sequence of asynchronous operations to be performed one after the other.

myPromise
  .then((result) => {
    // handle successful result
    return anotherPromise;
  })
  .then((result) => {
    // handle successful result of anotherPromise
  })
  .catch((error) => {
    // handle error
  });

The success callback function in the then() method can also return a value or another promise, which is passed to the next then() method in the chain.

myPromise
  .then((result) => {
    // handle successful result
    return anotherValue;
  })
  .then((result) => {
    // handle anotherValue
  })
  .catch((error) => {
    // handle error
  });

Here’s an example that demonstrates the use of the then() method:

const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve("hello");
  }, 1000);
});

myPromise
  .then((result) => {
    console.log(result); // 'hello'
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        resolve("world");
      }, 1000);
    });
  })
  .then((result) => {
    console.log(result); // 'world'
  })
  .catch((error) => {
    console.error(error);
  });

In this example, a promise is created that resolves after one second with the value 'hello'. The then() method is called on this promise, which logs the result to the console and returns a new promise that resolves after another second with the value 'world'. The second then() method in the chain logs this value to the console.

If any error occurs in the chain, the catch() method is called, which logs the error to the console.

const myPromise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('hello');
  }, 1000);
});

myPromise
  .then(result => {
    console.log(result); // 'hello'
    throw new Error('error');
  })
  .then(result => {
    console.log(result);
  })
  .catch(error => {
    console.error(error); // Error

In this updated example, the first then() method throws an error, which triggers the catch() method. The error is logged to the console, and the rest of the chain is skipped.

Here’s another example that demonstrates the use of the then() method to fetch data from an API and display it on a web page:

fetch("https://jsonplaceholder.typicode.com/posts/1")
  .then((response) => response.json())
  .then((data) => {
    const titleElement = document.createElement("h1");
    titleElement.textContent = data.title;
    document.body.appendChild(titleElement);

    const bodyElement = document.createElement("p");
    bodyElement.textContent = data.body;
    document.body.appendChild(bodyElement);
  })
  .catch((error) => {
    console.error(error);
  });

In this example, the fetch() function is used to fetch data from the JSONPlaceholder API. The first then() method converts the response to JSON. The second then() method creates two new HTML elements, sets their text content to the title and body of the data, and appends them to the web page. If any error occurs in the chain, the catch() method is called, which logs the error to the console.

Thank you for reading, and let’s have conversation with each other

Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.

Read more: