What is the purpose of the then method in Promises? How does it work?
What is the purpose of the then method in Promises? How does it work?
28126-Sep-2023
Updated on 26-Sep-2023
Home / DeveloperSection / Forums / What is the purpose of the then method in Promises? How does it work?
What is the purpose of the then method in Promises? How does it work?
Aryan Kumar
26-Sep-2023The then() method in Promises serves two primary purposes:
Handling the Success of a Promise:
Chaining Promises:
Here's how the then() method works:
You call then() on a Promise object and provide one or two callback functions:
The then() method returns a new Promise. This new Promise will be in one of the following states, depending on what happens in the callback function:
Here's an example illustrating how then() works for handling success:
In this example, when myPromise is resolved successfully, the callback function provided to .then() is executed with the resolved value, allowing you to handle the success of the asynchronous operation.
And here's an example demonstrating chaining Promises:
In this chained example, the then() method is used to chain two asynchronous operations together, ensuring that the second operation waits for the first one to complete before executing.