JavaScript Promise then() Method

JavaScript Promise.then() method is called when a promise is resolved.

Syntax

promise.then(onFulfilled[, onRejected]);

promise.then(value => {
  // fulfillment
}, reason => {
  // rejection
});

Parameters

It takes two callback function parameters:

  1. onFulfilled(required): A function to be executed if the promise is resolved successfully.
  2. onRejected(optional): A function to be executed if the promise is rejected.

Return Value

It returns that Promise is fulfilled or rejected, and the corresponding handler function (onFulfilled or onRejected) will be called asynchronously (scheduled in the current thread loop).

Visual Representation

Visual Representation of JavaScript Promise then() Method

Example 1: Using Promise.then() method

let promise = new Promise((resolve, reject) => {
 // Fulfill the promise with value after 500 ms
 setTimeout(() => {
 resolve("Data received successfully");
 }, 500);
});

promise.then(
 result => console.log(result), // onFulfilled function
);

Output

Data received successfully

Example 2: Rejecting the promise

Visual Representation of Rejecting the promise

let promise = Promise.reject(new Error('Something went wrong!'));

promise.then(null, err => {
  console.log(err.message);
});

Output

Something went wrong!

Example 3: Promise chaining

In promise chaining, the value returned from a .then()  method is used as the resolution for the next promise in the chain.

Due to this chaining mechanism, you don’t need to catch errors in each individual .then() If you put .catch() at the end of your promise chain, any errors in the promise chain will bypass the rest of the promise chain and go straight to your .catch() error handler.

let promise = new Promise((resolve, reject) => {
 setTimeout(() => {
 resolve(2);
 }, 200);
});

promise
 .then(result => {
 console.log(result); 
 return result * 2;
 })
 .then(result => {
 console.log(result); 
 return result * 3;
 })
 .then(result => {
 console.log(result); 
 });

Output

2
4
12

Browser Compatibility

  1. Chrome 32 and above
  2. Edge 12 and above
  3. Firefox 29 and above
  4. Opera 19 and above
  5. Safari 8 and above

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.