Why we use then() method in JavaScript ?

The then() method in JavaScript has been defined in the Promise API and is used to deal with asynchronous tasks such as an API call. Previously, callback functions were used instead of this function which made the code difficult to maintain.

Syntax:

demo().then(
    (onResolved) => {
        // Some task on success
    },
    (onRejected) => {
        // Some task on failure
    }
)

Note: demo is a function that returns a promise prototype.

Parameters: This function has two parameters to handle the success or rejection of the promise:

  • onFulfilled: This is a function that is called upon the success of the promise. This is an optional parameter.
  • onRejected: This is a function that is called upon the rejection of the promise. This is an optional parameter.

Return Value: This method can either return a Promise (if further another then() is called) or nothing.

Example 1: Passing no arguments



JavaScript

filter_none

edit
close

play_arrow

link
brightness_4
code

<script type="text/javascript">
    function demo() {
      document.write("Function called!!<br>")
      return Promise.resolve("Success");
      // or
      // return Promise.reject("Failure");
    }
    demo().then()
 </script>

chevron_right


Output: 

Function called!!

Example 2: Passing only the first callback

JavaScript

filter_none

edit
close

play_arrow

link
brightness_4
code

<script type="text/javascript">
    function demo() {
      document.write("Function called!!<br>")
      return Promise.resolve("Success");
      // or
      // return Promise.reject("Failure");
    }
    demo().then(
      (message) => {
        document.write("Then success:" + message);
      }
    )
</script>

chevron_right


Output: 

Function called!!
Then success:Success

Note that if the demo function returns a reject then it will generate an error.

Example 3: Passing both the arguments

JavaScript

filter_none

edit
close

play_arrow

link
brightness_4
code

    
<script type="text/javascript">
    function demo() {
      document.write("Function called!!<br>")
      return Promise.resolve("Success");
      // or
      // return Promise.reject("Failure");
  
    }
    demo().then(
      (message) => {
        document.write("Then success:" + message);
      },
      (message) => {
        document.write("Then failure:" + message);
      }
    )
</script>

chevron_right


Output: 

Function called!!
Then success:Success

Example 4: Chaining Multiple then() methods: Each then() can return a promise (a resolve or a reject) and therefore multiple then() methods can be chained together.

JavaScript

filter_none

edit
close

play_arrow

link
brightness_4
code

    
<script type="text/javascript">
    function demo() {
      document.write("Function called!!<br>")
      return Promise.resolve(1);
      // or
      // return Promise.reject("Failure");
  
    }
    demo().then(
      (value) => {
        document.write(value);
        return ++value;
      },
      (message) => {
        document.write(message);
      }
    ).then(
      (value) => {
        document.write(value);
      },
      (message) => {
        document.write(message);
      }
    )
</script>

chevron_right


Output: 

Function called!!
12

Example 5: Using then() as an asynchronous function

JavaScript

filter_none

edit
close

play_arrow

link
brightness_4
code

<script type="text/javascript">
    var demo = new Promise((resolve, reject) => {
      resolve(1);
    })
    let call = demo.then(
      (value) => {
        console.log(value);
        return ++value;
      },
      (message) => {
        document.write(message);
      });
    console.log(call);
    setTimeout(() => {
      console.log(call);
    });
</script>

chevron_right


Console Output: 

Promise {status: "pending"}
1
Promise {status: "resolved", result: 2}

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.