SharePoint Blog

A simple TypeScript Pattern for more synchronize asynchronous programming

Uncategorized//mvan//November 12, 2013//no comments

Now that the days have become shorter and it’s too cold for long nights on the terrace, I had some time available to play experiment with TypeScript. On CodePlex you’ll find a sample project that illustrates how you can use TypeScript for a more synchronized approache to asynchronous programming.

The AsyncObservable pattern is in fact a simple App that illustrates the power of TypeScript. Not that TypeScript is more powerful than JavaScript. But it helps to apply patterns used in object oriented programming when building powerful and robust JavaScript Apps.

The idea is simple and based on the Observable pattern and it’s no coincidence that it bears great resemblance to the KnockOut.js pattern.

The basic idea is that each asynchronous call to a service will result in a data set or more likely a JSON object e.g.

var egg = GetSomethingFromChicken();

Unfortunately you cannot write code like this when the call is made asynchronous because the method call will return nothing. You’ll need to define a delegate for this that will handle the callback as soon as the data is returned asynchronously.

With the AsyncObservable pattern, however, you can write code that bears some resemblance to the example above:

In this case the variable egg is defined as a Dependency object of type T as follows:

class Dependency<T>

Such Dependency classes will have a property of type Array<AsyncObserver> and here the Dependency stores a reference to object (that is an Observer) that created the Dependency in the first place.

Then through some plumbing, the Dependency is added to a queue of Dependencies that is managed by the Observer. Once all Dependencies have been added to the queue, its Enumerator-like behavior can be kickstarted like this:

// Now put the wheel in motion
if (this.MoveNext()) {
this.ResolveCurrent();
}

The MoveNext() method now points to the first Dependency object in the array of Dependencies and the ResolveCurrent() method will call the Resolve method on the Dependency object. This is the method that should be overwritten when the Dependency class is inherited from. It’s in fact the usual callback method.

To keep the wheel in motion it is essential that upon a successful callback the Dependency object notifies its Observer by calling the Resolved() method on itself.

Have a look at the code and any feedback and suggestions are highly appreciated.

Ps, since I’m a SharePoint Architect it will come at no surprise that the example code is for SharePoint. But it’s easy to see that this example is in fact not dependent on SharePoint technology. And I’m also aware that SharePoint can actually execute a batch of queries.