Skip to content

Instantly share code, notes, and snippets.

@dbrockman
Last active December 15, 2015 20:29
Show Gist options
  • Select an option

  • Save dbrockman/5318923 to your computer and use it in GitHub Desktop.

Select an option

Save dbrockman/5318923 to your computer and use it in GitHub Desktop.
function cachedAsyncFn(fn) {
var cached, queue;
return function (callback) {
if (cached) {
process.nextTick(function () {
callback.apply(null, cached);
});
} else if (queue) {
queue.push(callback);
} else {
queue = [callback];
fn(function () {
cached = Array.prototype.slice.call(arguments);
queue.forEach(function (cb) {
cb.apply(null, cached);
});
queue = null;
});
}
};
}
//// Example
var getConnection = cachedAsyncFn( asyncFnThatGivesMeAConnection );
getConnection(function (err, conn) {
// i have connection
});
getConnection(function (err, conn) {
// me too! no race condition...
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment