ptarjan / node-cache

A simple in-memory cache for nodejs
BSD 2-Clause "Simplified" License
1.59k stars 214 forks source link

Fetch or resolve flow #28

Closed Colex closed 9 years ago

Colex commented 9 years ago

Added the option use the cache within a non blocking friendly flow. It is based on Rails' cache fetch function but adapted to javascript and a non-blocking architecture.

The current API is for the fetch function is:

    cache.fetch("key").from(expensive_callback).then(result_callback)

expensive_callback is a non blocking function that calculates the value for the given key. It is only called if there is a cache miss. In the case there is no cache miss, result_callback will be called instantaneously with the value.

Here is one example of usage:

    function welcome_user(userid) {  
      cache.fetch("username-"+userid, 60000).from(username_from_database).then(print_welcome)

      function print_welcome(username) {
        console.log("Welcome " + username)
      })

      function username_from_database(cache) {
        pg.connect("postgres://localhost:3000", function(err, client, done) {
            query = "SELECT username FROM users WHERE id = " + userid
            client.query(query, function(err, result) {
              done()
              username = result.rows[0].username
              cache.resolve(username)
          })
        })
      }  
    }
ramonsnir commented 9 years ago

(I'm a maintainer of a downstream fork)

This is a very cool PR, except that you recalculate the function as long as the value is null (even that it is a proper own-property of the cache).

ptarjan commented 9 years ago

I don't think this method belongs in the cache layer. With ES6 Promises I can see an approach using standard promises, but not as this PR stands.