Promises Basics, Promise.then() Promise.catch():
Promises are the ideal choice for handling asynchronous operations in the simplest- manner.
- Benefits of Promises
- Improves Code Readability
- Better handling of asynchronous operations
- Better flow of control definition in asynchronous logic
- Better Error Handling
- A Promise has four states:
- fulfilled: Action related to the promise succeeded
- rejected: Action related to the promise failed
- pending: Promise is still pending i.e. not fulfilled or rejected yet
- settled: Promise has been fulfilled or rejected
---A promise can be created using the Promise constructor. --
Here is the syntax:
let promise= new Promise(function(resolve, reject){
//do something
});
- Parameters
- Promise constructor takes only one argument which is a callback function (and that callback function is also referred as anonymous function too).
- Callback function takes two arguments, resolve and reject
- Perform operations inside the callback function and if everything went well then call resolve.
- If desired operations do not go well then call reject.
Promise Consumers
Promises can be consumed by registering functions using .then and .catch methods.
1. then() : then() is invoked when a promise is either resolved or rejected.
Parameters: then() method takes two functions as parameters.
1. First function is executed if promise is resolved and a result is received.
2. Second function is executed if promise is rejected and an error is received.
Syntax:
.then(function(result){
//handle success
}, function(error){
//handle error
})
2. catch() : catch() is invoked when a promise is either rejected or some error has occurred in execution.
Parameters:
catch() method takes one function as parameter.- Function to handle errors or promise rejections.(.catch() method internally calls .then(null, errorHandler), i.e. .catch() is just a shorthand for .then(null, errorHandler) )
//handle error
})
Here is all code:
Comments
Post a Comment