Asynchronous JavaScript

Asynchronous Java Script
Asynchronous Java Script

This might not be a text for wizards of javascript. But I think, it might be very interesting for the other, much larger part of DOM/javascript developers population?

And (I dare to suggest) some from the narrow circle of self named javascript “ninjas” may learn how to apply object oriented programming paradigms and design patterns to contemporary javascript functional programming idioms.

For Asynchronous JavaScript 2/3 please click here.

Jan 23, 2009

The other day I wanted to have some kind-of-a AsyncResult (as it is well known to WIN32 developers) in JavaScript. I was very confident it will be a very simple but very clever and usefull javascript code.

Of course, I was somewhat wrong on the simplicity of developing this WIN32 idiom in JavaScript + DOM.

Necessary detour. Before some of you ‘acuse’ me of severe lack of knowledge, etc. I indeed know (and agree) that javascript does not do real multithreading. Same goes for the runtime environment used here, and that is DOM of course. But I also agree with everything conceptual in (for example) this article ( http://www.sitepoint.com/article/multi-threading-javascript ) . Are we ok now? We are? Ok then.

So, back to here and now. Here is my first version.

Have you expected this result? I will ‘reveal’ at once that the issue is that “this” inside the function doit() points to the window object. It does not point to the instance of the AsyncResult.

So why is this == window, inside doit() ? Also, this was happening inside the HTA program I used to test. Might this be the reason ? And how to assign to the AsyncResult, public properties ‘retval’ and ‘done’? From inside its private method doit() ? Was I doing it right?

Or is here some more fundamental issue presenting itself ? Maybe if I do the version with private properties, all will be magically solved? So here is my second attempt:

Also coded in a different, more condensed, paradigm of JS class declaration. Without using the ‘prototype’ feature. But alas, RESULT is still the same ?! Even with ‘this’ keyword, moved out of the equation.

How is this possible, what can we conclude here? Well I have quickly found that ‘done’ and ‘true’ are still introduced to the global space (actually added to the window object) even in this version. After short thinking, I concluded this can mean only one thing. setTimeout() executes doit() outside of the context of its immediate parent. It executes doit() in the context of the window object! So the next version, without setTimeout(), is here :

And indeed result is what we expected it to be. But with the whole starting idea in “ruins”. The code executes immediately. There is no any “spawning”. No even fake “multi threading” etc.. The call FP(this), inside the AsyncResult, may block for a long time.

What should I do? Some investigation, that much is obvious. Ian Smith, also sent me this link http://www.kryogenix.org/code/browser/secrets-of-javascript-closures/, where I have learnt (again?) about ‘that’. Or how to preserver ‘this’ as ‘that’, to be used inside closures.

So in essence my doit() method will have access to the current instance of AsyncResult through ‘that’, because ‘this’ is a ‘window’ object, because doit() gets executed by setTimeout(), So here we go: the next version :

And also AsyncResult() is not a closure any more, because of many FUD messages about IE’s inability to live with javascript closures.
(FUD = Fear Uncertainty and Doubt). And the result, what is the result ? Still the same..

And also an exception from the javascript engine saying : “Line 0, ‘that’ is undefined” . Which is is obviously coming from this line :

Which has to be rectifyied to look like this :

And all is dandy, besides the fact that we still have no result. And no AsyncResult, which is supposed to work and execute the worker “asynchronously” and keep the result.

Ok, not to despair. Let’s “take the walk”, and come back to this problem, with “fresh pair of eyes”.

2009-01-26

Ian sent me very comprehensive comment (see bellow). WIth lot of nice code, and a last two words of the comment: ” … normal JavaScript … ” . Ok, he is sincere at least ;)

I realise I am trying to emulate C++ thinking and paradigms in poor little JavaScript. There is a little known feature of C++ called Local Classes. You can define C++ class right inside a function :

There are limitation, Local C++ classes can not define static member variables (aka class properties in JavaScript) and can not access non-static member variables. Nice little encapsulation in practice (vs theory) useful example. In still the “top” programming language. Not to get scared, let us get back to our JavaScript issue at hand.

I wanted to convince myself that doit() inside AsyncResult gets called and executed, so I (rather weakly ?) resorted to good old alert().

Here is the doit() variant with alert() inside:

Since ‘that’ is actually a current instance of the AsyncResult, ‘alert(that)’ will call a toString() method on it and show us its current state of ‘retval’ and ‘done’ properties. And? Well “still no baby”, result is still the same :

How is this possible? Which ‘that’ is this then (sic) ? We just changed it’s properties, and we called it’s toString() in the very next statement, and still we see no change ?

This can mean that ‘that’ I am using/seeing inside doit() is not the same ‘that’ I have made before it with :

I have quickly added tid, to my toString(). And produced yet another AsyncResult version :

Now the result is still “wrong” with added information telling as that “timer ID” aka “tid” is also not the “right one” ?!

So doit() executes in some “quantum space” which is “nowhere”. Or as quantum mechanics are saying: “Where, is the wrong question to ask” …

Then I spotted a bug. In the last version above, I have ‘that.tid’ variable and I have ‘var tid’ variable. And this is a obvious mistake: they are not the same variables.

After ‘that.tid = SetTimeout(...‘ line, that.tid and this.tid will be the same variables. But not the same as ‘var tid’ which is private to the AsyncResult.

So in my toString() method I am using private variables, while in the doit() method I am using variables that do not exist before I make them! Therefore this line :

Creates new properties on the ‘that’ object. Which is actually ‘this’. It is NOT, using the private variables of the AsyncResult, at all! This is why they stay “untouched”. And this is how we do see them after calling that.toString() : just plain unchanged.

Ok, back to code, Might this be the next and the final version then?

The immediate result returned from spawn(), is as expected :

But, after 1000 microseconds (as requested), doit() got executed, and than FP(), in turn. And then I was greeted with a nice alert box saying :

Voila! Success at last. I have AsyncResult which works, as I wanted it to work in the first place.

It calls my function after requested amount of microseconds and it keeps the value returned.

This version catchess any exception made “inside” FP() call. The next step would be to extend the whole design so that it can be called with arguments.

Elegantly, as ever, of course.

NOTE: I did not know about Mozilla ‘workers’ idea ( https://developer.mozilla.org/En/Using_DOM_workers) before today. Also it seems quite different from my little pattern.

3 thoughts on “Asynchronous JavaScript”

Comments are closed.