/ Published in: jQuery
Basically, if the value has already been requested once before it's returned immediately from the cache. Otherwise, an AJAX request fetches the data and adds it to the cache. The $.when/.then doesn't care about any of this; all you need to be concerned about is using the response, which is passed to the .then() handler in both cases.
Deferreds are perfect for when the task may or may not operate asynchronously, and you want to abstract that condition out of the code.
Deferreds are perfect for when the task may or may not operate asynchronously, and you want to abstract that condition out of the code.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
var cache = {}; function getData( val ){ // return either the cached value or an // jqXHR object (which contains a promise) return cache[ val ] || $.ajax('/foo/', { data: { value: val }, dataType: 'json', success: function( resp ){ cache[ val ] = resp; } }); } $.when(getData('foo')).then(function(resp){ // do something with the response, which may // or may not have been retreived using an // XHR request. });
URL: http://stackoverflow.com/questions/4869609/how-can-jquery-deferred-be-used