Skip to content

Instantly share code, notes, and snippets.

@NeoPhi
Last active December 12, 2015 12:48
Show Gist options
  • Save NeoPhi/4774144 to your computer and use it in GitHub Desktop.
Save NeoPhi/4774144 to your computer and use it in GitHub Desktop.
// populate simulated local database with one value
var cache = {
'bob': 'DB BOB'
};
// simulated local DB
var db = {
load: function(key, callback) {
console.log('db.load', key);
process.nextTick(function() {
// simulate loading from local DB
callback(undefined, cache[key]);
});
},
save: function(key, value, callback) {
console.log('db.save', key, value);
// simulate saving to local DB
cache[key] = value;
process.nextTick(function() {
callback();
});
}
};
// simulated remote resource
var remote = {
load: function(key, callback) {
console.log('remote.load', key);
process.nextTick(function() {
// simulate loading from remote data source
callback(undefined, 'REMOTE ' + key.toUpperCase());
});
}
};
// create wrapper that has the logic to temporarily queue requests
function createQueueRequestHandler(fn) {
var queues = {};
return function(key, callback) {
console.log('handler', key);
if (key in queues) {
return queues[key].push(callback);
}
queues[key] = [callback];
fn(key, function(err, result) {
var callbacks = queues[key];
delete queues[key];
callbacks.forEach(function(callback) {
callback(err, result);
});
});
};
}
// function that specifies logic for loading data
var localThanRemote = createQueueRequestHandler(function(key, callback) {
db.load(key, function(err, result) {
if (err || result) {
return callback(err, result);
}
remote.load(key, function(err, result) {
if (err) {
return callback(err);
}
db.save(key, result, function(err) {
return callback(err, result);
});
});
});
});
// simulate calls
localThanRemote('alice', console.log);
localThanRemote('bob', console.log);
localThanRemote('alice', console.log);
// OUTPUT:
// handler alice
// db.load alice
// handler bob
// db.load bob
// handler alice
// remote.load alice
// undefined 'DB BOB'
// db.save alice REMOTE ALICE
// undefined 'REMOTE ALICE'
// undefined 'REMOTE ALICE'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment