![]() |
VOOZH | about |
The then() method in JavaScript is used with promises to handle asynchronous operations. It accepts two callback functions: one for handling a promise's resolved value and one for handling its rejection. It returns a new promise, allowing for method chaining.
Syntax
demo().then( (onResolved) => { // Some task on success }, (onRejected) => { // Some task on failure } ) Note: demo is a function that returns a promise prototype.
Parameters:
Return Value: This method can either return a Promise (if further another then() is called) or nothing.
Example 1: In this example, we have not passed any arguments.
Output:
Function called!!Example 2: In this example, we are Passing only the first callback.
Output:
Function called!!
Then success:SuccessNote: If the demo function returns a reject then it will generate an error.
Example 3: In this example, we are Passing both the arguments.
Output:
Function called!!
Then success:SuccessExample 4: In this example, we are using Chaining Multiple then() methods. Each then() can return a promise (a resolve or a reject) and therefore multiple then() methods can be chained together.
Output:
Function called!!
12 Example 5: In this example, we are using then() as an asynchronous function.
Output:
Promise {status: "pending"}
1
Promise {status: "resolved", result: 2}