1

i have SendRequest object and that class has a function like

        request: function(args)
        {
           return $.ajax.apply(null, args);
        };

then a lot of class use SendRequest object to get server response

        var prom = SendRequest.request(
            {
                type: 'GET',
                url: _this.uri 
            });

        return $.when(prom).done(function(response)
            {
                 .... do something 
            });

My goal is in SendRequest.request need to check on window.localStorage first. Whether already has a value or not, if has not any value before then send the request. Otherwise, if already value on localStorage then return $.ajax() object with that saved value before.

        request: function(args)
        {
            var ls = window.localStorage;
            var savedResponse = ls.getItem(args.url);
            if (savedResponse !=== null)
            {
               var result = $.ajax();
               result.responseText = savedResponse;
               result.readyState = 4;
               result.status = 'OK';
               return result;
            }
            else
            {
               return $.ajax.apply(null, args);
            }
        };

but unfortunately its did not work :( I've been looking but can not find some case like me

I already try this way to how to fool jqXHR to succeed always but its not help much

Community
  • 1
  • 1
leuza
  • 13
  • 4

1 Answers1

1

The reason this doesn't work is that although you've created a fake jqXHR object that's the response from $.ajax, that object isn't actually the parameter that's supplied to the .done callback - it's actually the third parameter.

Also, IMHO you shouldn't really use $.when to "promisify" a single non-promise object. It's intended to handle synchronisation between multiple promises and the fact that it wraps each non-promise into a new promise is just a side effect.

Instead, you should create a new promise that is already "resolved" with the appropriate data:

if (savedResponse != null) {
    return $.Deferred(function() {
        // retrieve relevant fields from localStorage
        ...
        this.resolve([data, textStatus, jqXHR]); 
    }).promise();
} else {
    // perform real AJAX request
    return $.ajax.apply($, args);
}

Alternatively, consider just memoizing the return data itself (for successful calls), not the whole response triple.

You may also find this presentation that I gave at jQuery UK 2013 of use - http://www.slideshare.net/RayBellis/memoizing-withindexeddb

Alnitak
  • 334,560
  • 70
  • 407
  • 495