DEV Community

Asad Mahmood
Asad Mahmood

Posted on

Promises in Javascript!!!

P..p..p..promise? Like a bond? Is this a developer blog or an English article? Well, apparently Javascript developers have to deal with promises in their coding life too, and this blog might just be the perfect spot for making you understand what this fuss is all about!

What exactly is a 'Promise'?

A promise, in the simplest language, is a container that is going to store some data in the future time. Going deeper, it is an object, that has multiple states and will return some values depending on if it was successfully resolved, or rejected.

A promise has 3 states, either pending, resolved(fulfilled) or rejected.

Initialising a Promise in Javascript

Code for initializing a promise

".then", ".catch" and ".finally" in Promises

Long story short, we can chain methods with promises. The '.then' method is chained with a promise which is then used to handle the promise when it is resolved i.e. the callback function inside the '.then' method is executed and it CAN return another promise(it's not compulsory though). The '.catch' method is chained with the promise and is executed when the promise gets rejected(this block is usually the exception handling block). The callback function which is inside the '.finally' method always gets executed, doesn't matter if the promise was rejected or resolved.

Promises chaining method syntax

Things I'd love you to know

  • Promises are asynchronous.

  • Promises have a different queue(from callbacks) in the background and the Event Loop prioritizes the promise queue over the callback queue, hence it won't execute any callbacks until all the promises inside the promises queue get exhausted.

  • Promises are generally preferred over callbacks because there is no possibility of falling into the callback hell when working with promises.

Top comments (0)