So let’s get started.
So what is a promise in the real world?
Suppose you want to write a function to add two numbers and if the sum is 5 then the function returns “success” and if it’s any other value then the function returns “failure”.If you are writing a function with a return statement then you can achieve this in the following way.
I have seen many complex explanations of this. But I will explain this in the simplest form possible, resolve is a method that we use to return a success response when the execution inside a promise is complete. A successful response can be anything ie it can be an object, a string, an array, etc.
reject is a method that we use to return a failure response when the execution inside a promise is complete. A failure response can be anything i:e it can be an object,a string,an array,etc.Below are some examples of how to use reject method
Now let’s see how to access a result from a promise. For this, we have two methods
then() and catch()
1).then(): The resolved response from a promise can be received using this method.
2).catch(): The rejected response from a promise can be received using this method.
Both of the above methods take in a function that takes in a variable and this variable name can be anything that you want.
Let’s use the example that we saw earlier. Below is the code for achieving this.
In this example, we can see that the function addTwoNumbers is called and a promise is executed and a response is returned. This function will execute asynchronously.
Hope you like the content.