Wednesday, September 10, 2008

Turning asyncronous interfaces into pseudo-synchronous interfaces...

... or making some callback-intensive JavaScript look less like bad LISP.

JooseX.DelayedExecution implements a type of mock object that implements the complete interface of the class object given to its constructor.
Every method call will schedule the method call with all its arguments for later execution on the original object.

This enables building asynchronous APIs that look like synchronous APIs.

Example:

This asynchronous code:
myFunc("foo", function (para) {
para.anotherFunc(function (para) {
para.yetAnotherFunc("bar")
})
})
can be turned into:
myFunc("foo").anotherFunc().yetAnotherFunc("bar")
by calling:
myFunc = function (para, callback) {
var result;
var process = function (result) {
delayed.__performOn(result)
}
... do something in an async callback that sets the variable result
return new JooseX.DelayedExecution(typeOfResult) // typeOfResult is the Joose class of the result object
}
I personally think that the latter is much more readable in certain circumstances. However, an unfortunate maintainer of the code might not know that the code is only hiding asynchronous execution which can lead to some hard to find bugs, because code is executed in random or at least async order.

For a use case of this technique, see the last post.

While this is probably so dangerous, that it should never be used, it was still fun to develop it.
Post a Comment