JS Promises: An Overview
A promise is an object which guarantees that there will be some value available in the future. This “some value” could be the expected return value or an error.
Promise object takes a callback function which accepts two arguments resolve and reject. This callback function is called executor function. It uses resolve function if the promise is successful and reject if it is not.
We can use then() to handle the promise in case of success . The then() block will be called when promise is successful.
Edit Code:- Online code
· You can see in above example during execution firstly the console.log statement is executed i.e. The first part printing string “This is our first part”.
· Then the third part to print in console “This is our third part” .
Lets look at the below similar code which is not using promise:-
You can notice in above example which is not using promise, that instead of waiting for returnValue variable to be assigned string value i.e. “This will print after 3 seconds” , JS simply prints value of the returnValue variable assigned initially i.e. null.
We can use catch() to handle the promise in case of failure. So, the catch part will be executed if promise was rejected. As shown in example below:-
In above example we have added the logic to print a error message in catch part. This logic was executed because we have used reject in executor function of promise to indicate that it was unsuccessful.