This blog will help you understand JavaScript Promise in a simple manner.
What if our application code want’s to execute long-running tasks and still be able to respond to other events and execute functions?
Asynchronous programming enables us to do this.
We can execute the long-running tasks, while also responding to other events. As and when the task is completed successfully or has failed, our program will be presented with the result. This is done by creating asynchronous methods.
A Promise is an object that is returned by asynchronous methods, just like a value is returned by a synchronous method. A Promise object is an agent or a substitute for a value that is not known yet when the promise is created. It allows to associate handlers and methods on the eventual success of failure.
Promise is in one of these three state
A Promise is said to be settled when it is in fulfilled or rejected state.
We create a Promise object by passing an executor function with two other functions as parameters. This promise will by settled when any of these two functions is called. The first function is for resolution of the Promise and second function is for Rejected state of the Promise.
Let us create a simple Promise object.
let myPromise = new Promise(function(resolve, reject) {
// "Producing Code" (May take some time)
let x = 0;
if(x == 0){
setTimeout(() => {
resolve("PROMISE RESOLVE");
}, 1000)
}
else{
reject("PROMISE REJECT")
}
});
console.log(myPromise);
setTimeout(() => console.log(myPromise), 500);
setTimeout(() => console.log(myPromise), 1000);