1

I have set of promises connecting to server like this one:

function getSomething(data, moreData, evenMoreData){
    var dfd = new jQuery.Deferred();
    Dajaxice.myProject.getSomethong(function(data){
        dfd.resolve(data.result);
    }, {'data': data, 'moreData': moreData, 'evenMoreData':evenMoreData});
    return dfd.promise();
}

I want to define proxy function called cache, working like this:

cache(getSomething, [data, moreData, evenMoreData])

This function should return promise. The promise will be resolved immediately if 'getSomething' result was found in cashe, otherwise, original 'getSomething' promise will be returned.

I started to write a function:

function cache(funct, args){
    if(Modernizr.sessionstorage){
        var dfd = new jQuery.Deferred();
        var hash = SHA256(WHAT?????);
        var cache = sessionStorage[hash];
        if(cache)
            dfd.resolve(cache);
        else{
           funct.apply(null, args).then(function(result){
              sessionStorage[hash] = result;
              dfd.resolve(result);
           });    
        }
       return dfd.promise();  
     }
    return funct.apply(null, args);
}

The question is: how should I compute storage key? (i.e. what should I put in place of WHAT???)

mnowotka
  • 16,430
  • 18
  • 88
  • 134
  • The key should be based on the data you're requesting, so having `WHAT` as `JSON.stringify(args)` would be a good start. – Matt Mar 15 '13 at 12:34
  • 1
    Not in my case - I have at least two functions sending an image to server and qiuite oftenit may be the same image. But for sure JSON.stringify(args) should be a part of the key. The problem is that there is no way of getting function name in a cross-browser manner. – mnowotka Mar 15 '13 at 12:36
  • 1
    In which case, I recommend you add a third parameter to your `cache` function, which is a unique name you assign for each function; then that, and the `args` can be used to form the key. – Matt Mar 15 '13 at 12:38
  • @mnowotka Yeah, but you can just simply set a name on a function and use it to generate a key. – freakish Mar 15 '13 at 12:39
  • @Matt - I will loose all the elegance of this solution. – mnowotka Mar 15 '13 at 12:40
  • @mnowotka: Then do what freakish suggested. You need to add a key *somewhere*. – Matt Mar 15 '13 at 12:41
  • 1
    @mnowotka Very simple. `var f = function(){};` and then `f._name="myname";` and use `funct._name` in your `cache` function. Note that you should not use `f.name` property as it is (or at least might be) used by browser. – freakish Mar 15 '13 at 12:41

0 Answers0