Skip to content

Instantly share code, notes, and snippets.

@wmertens
Created June 21, 2013 10:30
Show Gist options
  • Save wmertens/5830351 to your computer and use it in GitHub Desktop.
Save wmertens/5830351 to your computer and use it in GitHub Desktop.
Using cached promises for better resource use
# We have a function that loads some resource. It might get called multiple times by our application, for example a web server.
# We use a stored promise to serve as both a cache and a hook for multiple callers to get the same result
# JavaScript version at the bottom
Q = require 'q'
loadPromise = null
doLoad = ->
if not loadPromise
# get a fresh result
loadPromise = Q.delay(1000).then -> Date.now()
# after 1 second clear cache
loadPromise.finally -> setTimeout (-> loadPromise = null), 1000
return loadPromise
getLoad = (id) -> doLoad().then (data) -> console.log "#{id} got #{data}"
getLoad(1)
getLoad(2)
Q.delay(500).then -> getLoad(3)
getLoad(4).then -> Q.delay(1500).then -> getLoad(5)
### Result:
$ coffee pc.coffee
1 got 1371810343656
2 got 1371810343656
4 got 1371810343656
3 got 1371810343656
5 got 1371810346161
###
### Javascript code:
var Q, doLoad, getLoad, loadPromise;
Q = require('q');
loadPromise = null;
doLoad = function() {
if (!loadPromise) {
loadPromise = Q.delay(1000).then(function() {
return Date();
});
loadPromise["finally"](function() {
return setTimeout((function() {
return loadPromise = null;
}), 1000);
});
}
return loadPromise;
};
getLoad = function(id) {
return doLoad().then(function(data) {
return console.log("" + id + " got " + data);
});
};
getLoad(1);
getLoad(2);
Q.delay(500).then(function() {
return getLoad(3);
});
getLoad(4).then(function() {
return Q.delay(1500).then(function() {
return getLoad(5);
});
});
###
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment