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