Archive for May, 2011

Lazy loading asynchronous function with jQuery Deferreds

We are all well aware that out of process calls are very expensive, and a very common pattern, known as memoization, is used to “cache” the results, so a later call to the function returns a local result.
What do we do if that out of process call is asynchronous? For example an ajax request from a JavaScript application to a web service.
The problem with is that the first call to the function will fire off an asynchronous request.

var a = giveMeThingNumber(1);
console.log(a);

here the call to console.log may or not be occur before the function is ready. We must provide a callback to alleviate this situation:

var a = giveMeThingNumber(1,function(thing){
console.log(thing);
});

But the second call to this function is not asynchronous, and does not require this awkward callback. Additionally, we all have experienced the “callback” soup which comes about when we have to wait for a series of asynchronous calls to finish, before our “grand finale”.
Let’s see how to deal with all this. Read the rest of this entry »

1 Comment