HTML and CSS Reference
This function is using a closure to hold the cached version of the tasks in a variable called
tasks . If this is not null, then the tasks have already been cached, and are available for cli-
ents. If tasks is null an AJAX call is required to retrieve the tasks: this will both populate
the cache and return the tasks.
You can see that in either case a promise is being synchronously returned from an instance
of $.Deferred() to the client. You can also see that in both cases, this object is set to resolved
when the result is available for the client. This call automatically moves the promise into
the “fulfilled” state, and ensures any callbacks registered with done are invoked.
You will also see that this promise is relying on the promise returned from the $.ajax call
in the case where the server is invoked. To help you see the result easier, this code also has
added a 5 second delay in cases where we are performing an AJAX call.
In order to get the tasks, we invoke the getTasks method on this module. Just as with the
AJAX calls, we add a callback to the promise returned by getTasks:
promise = cachedTasks.getTasks();
console.log('I have finished')
If you execute this you should see the console print out “I have finished” after roughly 5
Now, run the exact same code again. You should see “I have finished” printed immediately
to the console, since this will use the cached version of the tasks, and therefore the result
will be available as soon as the callback is registered with the done method.
If you trace the code through you will see that the promise is actually already fulfilled when
we call the done method to add our callback, and therefore our callback is executed imme-
diately. In fact, even after the callback is executed, it is possible to add a second callback
to the promise:
console.log('I have finished again')
This will execute immediately, since the promise is already fulfilled.
The use of promises adds an extra dimension to callback-based programming. When writ-
ing asynchronously libraries from scratch it is highly recommended to consider basing
them on promises.