Promises in Javascript

Promises in Javascript

ยท

2 min read

A Promise represents the state of an asynchronous operation. This asynchronous operation can be anything i.e fetching data from an API, reading contents from a file, etc.

Before promises we had callbacks, but they had fewer capabilities and lead to a sloppy code. When dealing with multiple callbacks, our code will become a callback hell which becomes difficult to manage.

A Javascript Promise consists of four states:

  1. Fulfilled: The operation was completed successfully.
  2. Pending: The operation isn't completed, it's still in process.
  3. Rejected: The operation is failed.
  4. Settled: The operation is either fulfilled or rejected.

A promise can be created by using Promise constructor.

Now the above-created promise can be used as

The then handler is invoked when the promise is fulfilled while the catch handler is invoked when the promise is rejected.

Here in this case the catch handler is invoked as the number we have passed to the function is not even.

Chaining Promises

When the result of a promise is another promise, we have to chain them to get the results.

This method of handling asynchronous operations looks fine when we have 2 to 3 promises but it gets unmanageable when there are more than that. Then async await comes into the picture. They help you to handle multiple promises very easily.

That's it for now. Thanks for making it to the last. Let me know any feedbacks or suggestions you have for this article. Also, let me know if you want me to write on async await.

Connect with me on Twitter, Instagram & LinkedIn

Happy Coding!

Did you find this article valuable?

Support Deepansh Bhargava by becoming a sponsor. Any amount is appreciated!

ย