promise
A promise is used to handle the asynchronous result of an operation. JavaScript is designed to not wait for an asynchronous block of code to completely execute before other synchronous parts of the code can run. For instance, when making API requests to servers, we have no idea if these servers are offline or online, or how long it takes to process the server request.in the short term, we can say Promises are used to handle asynchronous Http requests.
Promise execution is asynchronous, which means that it's executed, but the program won't wait until it's finished to continue with the rest of the code.
Promises have three 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
rejected: Action related to the promise failed
pending: Promise is still pending i.e not fulfilled or rejected yet
Creating a Promise
The Promise object is created using the new keyword and contains the promise
; this is an executor function which has a resolve and a reject callback. As the names imply, each of these callbacks returns a value with the reject callback returning an error object.
const promise = new Promise(function(resolve, reject) {
// write code....
})
Let’s create a promise:
Output:
Success, this is promise
Using Promises
Promises can be consumed by registering functions using .then and .catch methods.
- then()
then() is invoked when a promise is either resolved or rejected.
Parameters:
then() method takes two functions as parameters.
.then(function(done) {
// the content from the resolve() is here
})
.catch(function(error) {
// the info from the reject() is here
});
- First function is executed if promise is resolved and a result is received.
- Second function is executed if promise is rejected and an error is received. (It is optional and there is a better way to hanlde error using .catch() method
Chaining Promises
Sometimes we may need to execute two or more asynchronous operations based on the result of preceding promises. In this case, promises are chained. Still using our created promise, let’s order an uber if we are going on a date.
Comments
Post a Comment