Skip to content

JavaScript then() method

  • by

The then() method in JavaScript is used with promises to handle the fulfillment or rejection of an asynchronous operation. It takes one or two callback functions as arguments, which are executed when the promise is fulfilled or rejected.

By using then(), you can perform actions with the result of a fulfilled promise or handle errors in a rejected promise. Chaining multiple then() calls allows you to create sequential asynchronous operations.

promise.then(onFulfilled, onRejected)

The then() method is called on a promise and takes one or two arguments: a callback function to be executed when the promise is fulfilled, and an optional callback function to be executed when the promise is rejected.

The onFulfilled is an optional callback function that is executed when the promise is fulfilled, meaning it successfully completes its task. The onRejected is also an optional callback function that is executed when the promise is rejected, indicating an error or failure.

Both onFulfilled and onRejected are functions that take arguments:

  • The onFulfilled function takes the value or result of the fulfilled promise as its argument.
  • The onRejected function takes the reason or error for the rejected promise as its argument.

It’s important to note that either the onFulfilled or onRejected callback will be called, depending on whether the promise is fulfilled or rejected. Also, you can chain multiple then() calls to handle the results of a promise sequentially.

Here’s an example of using the then() method:

promise
  .then(function(result) {
    // Handle the fulfilled promise
    // The result of the promise is available as `result`
  })
  .catch(function(error) {
    // Handle the rejected promise
    // The error or reason for rejection is available as `error`
  });

Use catch() or a second then() with an onRejected callback to avoid unhandled promise rejections.

JavaScript then() method example

Simple example code that demonstrates the usage of the then() method in JavaScript:

function getData() {
  return new Promise(function(resolve, reject) {
    // Simulate an asynchronous operation
    setTimeout(function() {
      var data = 'Some data';
      if (data) {
        resolve(data); // Fulfill the promise
      } else {
        reject('Error: Data not found'); // Reject the promise
      }
    }, 2000);
  });
}

// Using then() to handle the promise
getData()
  .then(function(result) {
    console.log('Data:', result);
  })
  .catch(function(error) {
    console.log('Error:', error);
  });

Output:

JavaScript then() method

Comment if you have any doubts or suggestions on this Js basic methods tutorial.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading