When you need it !

Callback

For those living under a rock in the world of Web Dev and who missed the big buzz when Promises in JavaScript were the talk of the town. I present this article. Yeah, I am one of you and did not really bother to check them out because most of my routine tasks were being performed using Callbacks. Now, since I think I have some time to look into it ( free from my BackEnd work) I am interested in writing about them.

Notes to self : I Promise that this won’t be a long post. I Promise that this post will give only an elementary idea of Promise in JS because I myself found it very difficult to find something, giving you a very elementary idea of the same. I also Promise that I will not keep your hanging and add all the relevant context that you need to know/understand in order to understand JavaScript Promises, like async.

The mentioned code extract may or may not return the Alphabet output A B and C in order. It may be A C B too. Why? Because B is executed asynchrnously. Because loading the X.html page may take time and is executed as soon as its available and the extract console.log("C"); does NOT wait for it to complete.
See this code extract :
tweet = A(); //Line1
//Do something with tweet
doSomeImportantThings; //Line2

So, line number 2 will not be able to execute until Line 1 is done and the next things are done as JavaScript is single threaded.

Here, A does stuff asynchronously and Line2 will not wait for A to finish. This is the beauty of Asynchronous execution. But, at times, when things are asynchronous it may lead to trouble if we exactly need the things to happen in some order.

Consider the scenario below :

Load a Loading GIF file to indicate page is loading

Load Images

Load Fonts

Load Everything else relevant

Only if all are loaded, remove the GIF Loader and display the content

Due to JavaScript’s synchronous execution and single-threadedness the above order may not be executed as we desire. Say, Images and Fonts are from third party websites like Google and hence, asynchronous loading is necessary. So, it will take a while. Not sure how much though and the Loader will also not know what is the finishing time. This is sad. Check Pseudo code :

As you can tell, based on your internet speed and mostly any damn internet speed, loadLoaderGif() and unloadLoaderGif(); will execute almost immediately whereas the async functions will take their own time for fetching images and laying them at the right places etc. So, the whole purpose has been defeated yeah ? Ok. To solve this our forefathers already included callbacks in JS.

Now, how about this???
loadLoaderGif();
//I am a magical block of code and I ensure you that I will execute
//All of the loaing n crying, ranting stuff and then only let the function next
//to me execute
unloadLoaderGif();

See the middle block of comments !!!!
Yeah, Promises come into the picture now.