Javascript - Consuming a Promise with then() and catch()

Introduction

Once a promise is created, it can be passed around as a value, representing a placeholder for a future value.

This value can be consumed when the promise is fulfilled using .then() method.

This method takes a function that will be passed to the resolved value of the Promise.

const p = new Promise((resolve, reject) => resolve(42)); 
p.then((val) => console.log(val)); // 42 

Every promise must have a .then() method that actually takes two possible parameters.

  • The first parameter is the function to be called when the promise is fulfilled.
  • The second parameter is a function to be called if the promise is rejected.
  • p.then((value) => { console.log("Promise Fulfilled:", value) },
  • (error) => { console.log("Promise Rejected: ", error) });

If a given promise always gets resolved, we can omit the second parameter for simplicity.

The following example shows that the customer gets his pizza five seconds after the order:

const pizza = new Promise((resolve) => { 
       console.log("Getting your pizza in 5 seconds..."); 
       setTimeout(() => { 
              resolve("Onion Pizza"); 
       }, 5000); 
}); 

pizza.then( 
(item) => { console.log(`Order Received: ${item}`) }, 
(error) => { console.log("Something went wrong with your pizza") } 
); 

// Getting your pizza in 5 seconds... 
// Order Received: Onion Pizza 

Related Topic