Promise in JavaScript is similar to promise in real life.
In our day to day life we promise something, for example your boss asks you to deliver a particular task within given timeline. we say, yes I will deliver it within given timeline. It's a promise.
Now there two situations with your promise, either you will deliver task within timeline or not.
Same concept is applicable with JavaScript Promises, either promise will be resolved or it will be rejected. ( i.e. either you will be able deliver task on time or you will not be able to deliver on time).
for these two situations, your boss will plan accordingly.
Technically your boss has two functions (plan in real life), one he will execute when you will deliver task on time and other if you will not deliver task on time.
lets see how to create and use Promise in JavaScript.
Promise is a object, which has a executor (function) which takes two callback functions (resolved, rejected)
var deliveryPromise=new Promise(function( resolved, rejected){
// your are coding and trying to deliver on time;
// if you are success then you have to call resolved() function.
// if not then you have to call rejected() function.
});
you are giving this promise to you boss as I wrote previously your boss has two function( In real life these functions (or plan) in his mind)
deliveryPromise.then(function(){
// this function will be executed when resolved() called in above code.
// Your boss's next plan if you are able to deliver on time
}).catch(function(){
// this function will be executed when rejected() called in above code.
// Your boss's backup plan if you are not able to deliver on time
}).finally( function(){
// this function will be always executed, in both cases (resolved ,rejected)
});
Promise has 3 states : Pending ,Resolved, Rejected.
Definition from MDN :The Promise object represents the eventual completion( or failure ) of an Asynchronous operation, and its resulting value. "
Example :
Suppose your mom is promising you, to buy a new mobile for you, if she will get bonus more than 10000 this month. (if she will get bonus more than 10000 then promise will get resolved otherwise rejected).
No comments:
Post a Comment