Friday, 5 December 2014

$.when then and then JavaScript...a single-threaded-monolith-of-interpreted-disaster-for-maintenance :) !

The funny thing is that when JavaScript and jQuery are used in conjunction, it can often be a little puzzling as to which event is getting propagated when and whether to use event propagation or event bubbling to ensure that the right sequence of events have been handled or not and when all these aspects did get resolved, as I sat back to contemplate on the immense, combined destructive power of JavaScript and jQuery together not through any power tools but in the way that they resolve each others' problems such that the end result looks more like a compound that could have confounded the best of scientists put together, I realized that that here is an example that could be likened to the splattering of debris from space, to the 'distributed' missile that "Iron Man" goes to demonstrate to the terrorists, to the 'open for interception' messages strewn across the social media that eventually conjoin (if such a word exists) like in the Terminator (the villainous ones who roll back from liquid droplets to human form!) and serves, best, as the prototype to the theory that if art is a reflection of life then software, AI and design patterns (software ones that is) are 'represented' algorithms of human's interactions. 

Tough and tasking, this may be, I can understand, especially if you are reading my blog with a cuppa and thought it would be a breeze to read through my blog ! 

But it was necessary, believe you me, this roundabout, Thomas Hardy-like obscurity-bordering-on-controlled-rant narrative because it is only upon describing the problem statement in detail can you understand or comprehend what the above observation, and the title above it, means !

The problem statement is the usage of two asynchronous mechanisms (not methods) that need to 'listen' (change in location position co-ordinates), 'communicate' (save the change in location to the DB) 'intelligently' (i.e., not as a dumb client that can simply wait for any response and 'redirect' as if passing the blame to the next page!) through an AJAX call to a VB.Net WebScript Service method (which means server-side technology) via JavaScript, as a JSON object, and to finally (the compound), ensure that the GeoLocation call has been successfully completed before calling the Web Service Script method and on return (I had never experienced before (in my mind, that is) how many different places that a call to a function could return to - a JavaScript call can return to any DOM object, it can return to the last line of the calling function, it can return to a callback, 

(Ah, we all know that? Read on for a few minutes more and you will realize why dismissive attitudes are not only demeaning to progressive minds but also needless !))

behave like the dancing hurricane (or typhoon) that deceives to deceive - that is quite a lot of integrity for a scripted, interpreted language,

despite all that junk said about JavaScript being a single-threaded-monolith-of-interpreted-disaster-for-maintenance - ah, so here we are,

So. when a call to a location services and a call to save the consolidated data occur synchronously but also must ensure that the save data will occur only upon successful location seek, the one best way that is known to be used is the 'callback' - which is much like an illusion in JavaScript because, whether you like it or not, the subsequent lines of code after the location seek will be executed.

For instance,

// Lines n to n+25 in "some .js file"
function somefff....{
    if (navigator.geolocation) {
        var positionOptions = {
            enableHighAccuracy: true
Line 1     navigator.geolocation.getCurrentPosition(function success1(position) {
                var brlat = position.coords.latitude;
                var brlongitude = position.coords.longitude;
                sessionStorage.setItem("breakStartlocation", brlat + "," + brlongitude);
             }, function (err) {
                 wctr = true;
                 sessionStorage.setItem("breakStartlocation", strlocationErrorMessage);
        } else {
              alert("Location setting is not enabled or supported in your current browser!");

// Lines n+26 

 Line n if (confirm("You have disabled location seek. Press Ok to reset your browser settings or Cancel to deny location information.")) {


else if ....{}

// Lines n+200 to 30 (or so!)

        options.success = function (result) {
            alert("Break saved");
        options.error = function (err) { alert("Error");}
Line n+1        setTimeout(function() {
Line n+1+1 (for the sake of brevity!)

return saveResult;


In the above lines of code, Line 1, Line n and Line n+1 and Line n+1+1 fall into a sequence because of JavaScript's execution mechanism, despite the logical requirements, which is to ensure the sequence of the calls. Not a big deal, as the flippantly inexperienced may quickly quip not knowing that the Geolocation provider has made their service an async service, by specs and design!

This means that the calling code or object would have continued on to display the Confirm message, without waiting for the user to acknowledge to the browser (that has already received the location provider's request to seek out the user's location) that their location could be sought.

It also means that the Line n+1 Ajax call to the webservice method is already underway (even the Confirm dialogs can be of no use if the user clicks the Ok buttons real fast!) and while we are at it, we may as well consider the fact that the Ajax call may have already returned back to the calling page ie. Line n+1+1, too, has executed. So, the calling page that has to display (render) a different set of buttons and UI elements (CSS elements), must have a mechanism to determine if the save data call has been a success and here, is where jQuery and Ajax come to the rescue of JavaScript.

The zest for patching up is an age-old technique that has both its 'pros' and 'cons' (probably why it is called the 'jugaad' in India) and this zest is evident with the way many JS developers and designers felt and being more seamlessly tuned to each other's needs than the 'boxed' up Microsoft or Java developers, jQuery is almost the way a poor man or woman cater to their family, a 'patch' here, a patch there - "Oh, does the event bubble up to the document object? ('Daya', in Hindi, means compassion but since CID, a Hindi TV serial of monumental moronity, has become symbolic of a person breaking open doors, unlawfully, it has now become synonymous with 'show some compassion for wooden doors'. What I mean is, desist. Desist from that lust to argue that a Document is part of the DOM.). Let us change the Ajax calls to return to the DOM than to elements or objects..."

This comparison is not meant to be derogatory because it is a "kind of" representation of how nature, too, responds (though in a more perfectly harmonized manner), adjusts and responds to adjustments again (much like the shifting of the tectonic plates to create mountains to change the paths of rivers to cause floods to cause erosion again to level up).

So, to keep the thread of continuity tight as I lead you through this incredible maze of Ajax event handlers, DOM and plain old JavaScript timeouts, let me quickly warm you up to the "Promise" offered by AJAX/jQuery.

Unlike the build-up, this post's ending is pretty abrupt - all you need is a $.when to wrap around the method call  -

// The calling method from another page (can also be interpreted as a DOM, for the sake of understanding this example.) From different page.aspx


and a .then() with func and func1 representing the 'success' and 'not success' in the function call when it completes! So, what is the promise? All this can be handled with simple callbacks.

The 'Promise' is that you can line up any number of sequence to calls made to asynchronous methods

(ie., methods that make asynchronous calls but which desperately need a mechanism, not provided in JavaScript, that execute async calls, synchronously, but require coherence in sequence to enable manageable logic in execution, not just to tackle complex business models and demands but also for the benefit of testing frameworks and testability)!

but more importantly, as I experienced, I could manage two 'disconnected' events that had 'committed' synchronous activities attached, 'post-' the async call, that relied not on the 'traditional' HTML post or 'form' methods or elements but on CSS elements, which meant callbacks-had-to-'trigger'-an-execution-thread on the client-side upon successful completion (or not), which cannot happen until it happens at the DOM level and which the Ajax's document level event handlers like AjaxStart, AjaxStop, AjaxComplete, AjaxSuccess and many more provide.

But the real joke is in the parameters to the then() method - they, too, execute synchronously !! :D

No comments: