Horje
JavaScript Promise then() Method

JavaScript Promise then() method is called whenever a promise is resolved. It takes data from the resolved promise. It can take up to two arguments which are callback functions for the fulfilled and rejected cases respectively. Just like the catch() method it also returns a Promise so it is used to chain Promises. 

Syntax:

then(successFunc, rejectFunc)

Parameter: It usually takes up to two parameters and the second parameter is optional. These parameters receive data from the Promise

  • successFunc: This asynchronous callback function gets executed when the Promise is resolved
  • rejectFunc: This asynchronous callback function gets executed when Promise is rejected

Return Value: This method returns a promise which is in the pending state even if the previous promise is finished.

Example 1: This example uses the then method to handle the resolve state of a promise.

Javascript

let prom1 = new Promise((resolve, reject)=>{
    resolve("Success");
})
.then(e=>{console.log("Hello Successful")})

Output:

Hello Successful

Example 2: This example uses then method to handle reject of a Promise by passing the second argument.

Javascript

let prom1 = new Promise((resolve, reject)=>{
    reject("Rejected");
})
.then(e=>{console.log("Hello Successful")}, e=>{console.log(e)})

Output:

Rejected

Example 3: This example uses then method to chain promises.

Javascript

let prom1 = new Promise((resolve, reject)=>{
    resolve("Successful");
})
.then(e=>{
            console.log(e)
            return "Completed"
      })
.then(e=>{console.log(e)})

Output: The first then returns Promise which is handled by the second then block

Successful
Completed

Supported Browsers:

  • Chrome
  • Edge
  • Firefox
  • Opera
  • Safari

We have a complete list of Javascript Promise methods, to check those please go through the Javascript Promise Reference article




Reffered: https://www.geeksforgeeks.org


JavaScript

Related
How are characters stored in JavaScript ? How are characters stored in JavaScript ?
How are strings stored in JavaScript ? How are strings stored in JavaScript ?
How to create Infinite Scrolling using onScroll Event in JavaScript? How to create Infinite Scrolling using onScroll Event in JavaScript?
What is the JavaScript version of sleep() method ? What is the JavaScript version of sleep() method ?
How to open URL in same window and same tab using JavaScript ? How to open URL in same window and same tab using JavaScript ?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
14