Hey, I just met you / And this is crazy / But here’s my callback / So call me maybe

Analysis : Callbacks vs Promises

Priyadarshi Dasgupta
codeburst

--

Folks, before you delve your gray cells into the aforementioned modified lyrics from Call Me Maybe (Carly Rae Jepsen) :) , let us make peace with the fact that this article in every way is an analytical article to understand the asynchronous approach of Javascript!

However if you wish to secretly fill your ears with the melodious number, I am leaving the link here: https://www.youtube.com/watch?v=fWNaR-rxAic

Asynchronous approach and Javascript(JS) were born hand in hand. This is entirely due to the design structure of JS, which forces it to pair up with the world of asynchronous tools. As there is only a single thread of execution in JS, aligning with the synchronous approach gives into lots of idle execution time, which could be effectively used for carrying out other tasks [barebones of asynchronous approach]

The following figure might help you in grasping the idea: Please note that the X axis is the incremental time and Y axis are the events ->

Synchronous Activity in which every event fires only after the previous is done
Asynchronous Activity in which there is no waiting for the other event to finish.

Now the question is how do we achieve async! I will introduce two competitors who had valiantly fought the async battle namely Callbacks and Promises!

Hi, My name is PD :) and I am trying to set up a date with this girl from next door, Bee [her nickname]. In a desperate attempt to fix the date, I dial her number with a tinge of hope! She answers the phone and I am hesitant to ask her out. With great trepidation, i ask her and she replies “Aaaa..PD.. I will let you know within an hour”. I take that to my chin and continue to do my daily activities like bathing, driving to office, having breakfast.. I mean to say, her answer doesn’t stop me from pursuing the other essential activities which i must DO! Later, after an hour, I will get to know her answer!This story has close correlation to CALLBACKs in Javascript.

stack of callbacks

Callback is an approach where the thread do not essentially wait for an event to finish! If there is a time intensive event, the thread will continue to perform all events and push the execution of the time intensive event to a callback. The purpose of a callback is purposefully handled by a first-class function[worker thread], it executes the time intensive event and once the event completes, notifies the main thread about the status. Please follow the example:

Code:

Console:

Explanation:

The first two results are me doing the daily activities, whilst I am still expecting a YES/NO response from her. So, the ReplyFromBee function is basically a callback, it takes care of the response from the charming lady and whenever she is ready to give me the response, the function takes care! [Here i have used the setTimeout function to emulate the condition and given it a wait time 4000 milliseconds]. The asynchronous mature is hence established!

Promise in JS

Now back to the original story, I [PD] go around preparing for the date, but I have a dilemma. Will she say YES or will it be a NO? However, to boast my status among my pals, I continue to hype and prepare for the Date, in case she says YES. Depending upon her response, I would have to book a table, rent a Tuxedo and pick her up with my AUDI.[though i have none in real]. Phewwwwwwwww!!

If we analyse the above situation, we find that my request for a Date can be classified into three plausible scenarios:

  • Pending: Which is what my status is now!
  • Resolved: She says YES and i get a DATE :) :) :) :)
  • Rejected: :( :( :( :`( :(

Promises in Javascript are promises in real life. Bee promised to give her answer within some time frame, and I have three possible scenarios [states in official terms]. Depending upon her answer, I can take further steps, neither before , nor after. Let us delve into a Promise code:

Code:

Code Explanation:

The function willIGetADate [ Promise creator ]uses the JS promise constructor, which takes into account two arguments namely resolve and reject. Depending upon the value of the boolean variable BeeResponse, we take subsequent action, and pass the result within the resolve or reject params. The askBee function on the other hand is a Promise consumer i.e. it consumes the willIGetADate promise and outputs the possible result. Please pay attention to the usage of .then and .catch, which acts upon the Promise creation method and passes the value of fulfilled. But, What is the value of fulfilled? The fulfilled value is exactly the value you pass in your promise resolve(your_success_value). Therefore, it will be date object in our case. Similarly, in the .catch portion, the error.message is nothing other than the value we pass in reject(your_fail_value). Therefore, it will be reason in our case. Let us verify the result.

Console output:

when the BeeResponse is true, i get a detailed object with all the properties i desire. :)
when the BeeResponse is true, i get a reason!! :(

The fundamental difference between both of them, each serving the same purpose, is their composability, which basically means that combining multiple promises [promise chain] works, but combining multiple callbacks gives way to messy code [callback hell]. Even from a readability standpoint, Promises look succinct, clear and stands out from callbacks.

Mind you, it is fair to say promises are just syntactic sugar. Everything you can do with promises you can do with callbacks.

It’s good to know that there is a new kid in the block named Observables, which reduces the effort to introduce concurrency in application by forcing the application to register to a stream of events. I will discuss this in the next meet.

Till then lemme go and spend time with Bee! Happy Coding.. :)

--

--