How to Cache Results from Asynchronous Calls in AngularJS

Coming from many years of Java programming, I started to program a lot with JavaScript from a few months ago. Overall the programming fundamentals are the same except the some differences on the language syntax. These differences can be adapted over the time, not quite easily, but gradually easier with more practices.

These days I found myself typing double quote for Java string and single quote for JavaScript strings, even though the double quote works just fine with JavaScript. But keep that difference helps remind me that it’s Java or JavaScript.

Lost VMs or Containers? Too Many Consoles? Too Slow GUI? Time to learn how to "Google" and manage your VMware and clouds in a fast and secure HTML5 App.

One thing I found hard to twist mind is how to deal with the asynchronous calls in JavaScript. Because the Javascript does not have a good threading model, most libraries that take time are designed as asynchronous, meaning you don’t get what you want immediately, but a handle to what you want later once the work is done. Why? That is probably the only way not to block the main thread, or you would get a non-responsive GUI.

In most cases, the asynchronous methods are not hard to use. After reading a few samples, you can be an expert to make such invocations. For example, you want to assign a value from a HTTP call whenever successful. With the HTTP library, the returned object makes it easy to handle value assignment.

There is a hard part with these asynchronous methods, however – how to cache results from asynchronous calls?

Here is the use case: when a Web application first loads up, it grabs a value using a HTTP call. When HTTP call finishes, the value can be assigned. Because the value does not change, I would like to cache it with a temporary variable. When the value is needed the second time, the value should be returned immediately without making more HTTP call.

Simple enough use case, but I found it’s pretty hard to implement. The difficulty is that the return is different the first time and after: the first call has to return a promise because the underlying HTTP library is out of anyone’s control; the later calls should return a value immediately.

After researching and thinking, a solution comes up with the help of $q service.

  var value;
 
  this.getValue = function() {
    var deferred = $q.defer();
    if(value) {
      deferred.resolve(value);
    }
    else {
      $http.get('...').then(function(res) {
        value = res.data;
        deferred.resolve(value);
      });
    }
    return deferred.promise;
  };

With the above code, the value is cached in a service function. When the value is not ready, it goes to fetch it using $http service. If the value is there already, simply wrap the value with resolve() method. Although the value from 2+ calls is wrapped as a promise, but that value is immediately available.

The way calling it is also simple:

  aService.getValue().then( function (data) {
    $scope.value = data;
  }
This entry was posted in Software Development, Uncategorized and tagged , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

  • NEED HELP?


    My company has created products like vSearch ("Super vCenter"), vijavaNG APIs, EAM APIs, ICE tool. We also help clients with virtualization and cloud computing on customized development, training. Should you, or someone you know, need these products and services, please feel free to contact me: steve __AT__ doublecloud.org.

    Me: Steve Jin, VMware vExpert who authored the VMware VI and vSphere SDK by Prentice Hall, and created the de factor open source vSphere Java API while working at VMware engineering. Companies like Cisco, EMC, NetApp, HP, Dell, VMware, are among the users of the API and other tools I developed for their products, internal IT orchestration, and test automation.