Promise in JavaScript
What it means ?
Promise in javascript means the same as in real life you promise somthing to your friends,the either your fulfit it or you can’t . Similarly a Promise might either be resolved or rejected
Producing Code
It is that part which does something and returns the result . For instance , an API call which returns the data .
Consuming Code
It is the part which wants to utilize the result of “Producing Code” after its ready.
Promise
A promise is a JavaScript object which connects the producing code with consuming code.
How it works ?
A promise has three important states whenever it is executed-pending , resolve and reject
Initially , the state is “pending” then it changes to “fulfilled” if resolve is called or “rejected” if reject is called.The resolve and reject callbacks are provided by JS, so we don’t need to cteate them.
Resolve
Let’s see a simple example :
Here , we declare a promise and then resolve it after 1000ms .After this is resolved,we can access it using the “.then ” method provided by Javascript .The function passed to new Promise is called “executor”. whenever a new Promise is created the executor function is called automatically .This is where our producing code lies which eventually produce the result .And the”consuming code” can be within the “.then”method.
Reject
Let’s see a simple example :
Here, we reject the promise by throwing an error , The promise will be rejected after 1000ms .After it is rejected , we can catch it using the “.catch” methiod provided by Javascript , Since the promise returns an error object, it has various properties . In order to access the message we use the “.message” property.