Manage cache synchronously in js

I support cache in JavaScript using jquery in a global cache variable.

Whenever new information is obtained using AJAX, it is added to the cache.

If it's not in the cache, I want to AJAX it from the server.

I want to implement a request-by-request function and use it like this:

$("#label").html(GetName("user123"));

Where GetName () should look like this:

function GetName(username) {
    if (Cache[username] != null) return Cache[username];
  else
    return QueryUsernameFromServer(username)
}

QueryUsernameFromServer () should look like this:

function QueryUsernameFromServer (username) {
    return $.ajax(…);
}

However, $ .ajax is asynchronous, which means that it cannot wait for the value (and therefore cannot return it).

Using $ .ajax mode in sync mode is strongly discouraged (the browser freezes and it does not support JSONP), http://api.jquery.com/jQuery.ajax/

, http://www.techfounder.net/2008/05/17/simple-javascript-cache/, . .

" " js ajax ?

+5
2

, AJAX... ... "A" .

, . :

function getName(username, callback){
  if(cache[username]){ 
     // cache hit, immediately invoke the callback
     callback(cache[username]); 
  }else{ 
    // assumes this query function updates the cache and invokes the
    // 2nd parameter when it completes
    queryUsernameFromServer(username, function(){
      // invoke the callback now
      callback(cache[username]);
    }); 
  }
}

:

:

var name = getName('jvenema');

:

getName('jvenema', function(name){

});
+5

jQuery 1.5+, .

function GetName(username) {
    if (Cache[username] != null) return $.when(Cache[username]);
  else
    return QueryUsernameFromServer(username)
}

GetName('jvenema').done(function(name) {

});
+1

All Articles