DEV Community

Cover image for Dealing with asynchronous data in Javascript : Promises
Swastik Upadhye
Swastik Upadhye

Posted on

Dealing with asynchronous data in Javascript : Promises

What is Promise ?

Well, we use this word in our daily life so many times. We often make promises to ourselves , sometimes we keep them and sometimes break them 😉. Does it have the exact same meaning when it comes to Programming ?

Well, sort of!. To make this understand we should recall what is the purpose of handling asynchronous data. In an asynchronous manner, what we are doing, first we complete the primary task and then only we try to accomplish susequent task.Here, primary task is a kind of a promise. Now, let us find out how are they exactly behave in programming context.


Promise

  • Promise is an object that produces a single value either resolved or rejected ( make them / break them )
  • Promise has three states : Pending , fulfilled & rejected. They are eager i.e as soon as we call promise constructor, it starts the given task.
  • It accepts two functions : resolve & reject
  • Promises are thennable i.e we can execute the subsequent task using then method.

Image description

  • In the above code example, we are going to perform one of the two actions depending on the lock down status.
  • If there is no lockdonwn then we can go for a trip otherwise we have to sit in our home.

Now, take a practical example. A user is trying to sign in a website. Here, authentication api is called if it is going to return a token then only user is allowed to see dashboard.

Image description


Promise Chaining

  • If we are having multiple asynchronous tasks which depend on one another then we can chain them using then method
  • As promises are thennable we can chain n number of promises one after another.

Image description


Handling Errors

  • Errors can be occured because of multiple factors. So it is neccessary to handle them rather than providing a broken page.
  • Promises do have a catch method. We can chain it to promise object.
  • The code example shown below illustrates that if there's an error then he/she will redirected to the signup page.

Image description


Advantages & Drawbacks

  • We don't need to nest the functions one into another, as it is done in the callbacks.
  • It improves the code readability and provides a better way of handling errors.

  • As promises are eager, once fired we cannot cancel them.

  • The programming execution doesn't stop at the moment until the promise is received. The program continues to run further line by line.

  • Also, still the code doesn't look synchronous.

So to overcome the drawbacks, async-await is introduced
We will see what are they and how they work in the next blog.

Thanks for reading the article!!!.Feel free to drop me here if you have any doubts and suggestions!

Discussion (0)