JavaScript promises are same as the promises we make in real life. The commitment we make to someone.
Example: “I promise I will code daily.”
Now this promise has two results.
- You either fulfill it (resolved).
- or You’ll break it. (rejected).
Now, let’s have a look at the syntax.
Syntax:
Promise syntax is super easy just like how we create a constructor. But here we pass a function with two parameters resolved(value) and reject(error).
Here, we've made a promise that value of a=1+1 should be 2. If it is 2 then promise is resolved else it is rejected.
Now, let's learn how we can interact with these promises.
Here, we will use two methods to check whether our promise has resolved or rejected.
- then() will return resolved.
- catch() will return rejected. as a callback message.
Benefits of using "Promises".
- Improves code readability.
- Better handling of Async operations.
- Provides a better flow of control while defining async logic.
- Better error handling.
Hope you got the concept of how Promises work. If you did please follow and share.
Even if you didn't, that's fine you can do it anyway .😄
Top comments (0)