Skip to content

Instantly share code, notes, and snippets.

@nemtsov
Created August 7, 2013 22:19
Show Gist options
  • Save nemtsov/6179373 to your computer and use it in GitHub Desktop.
Save nemtsov/6179373 to your computer and use it in GitHub Desktop.
A way to give existing callback-based libraries a chainable interface.
module.exports = Lib
function Lib() {
this._queue = []
var methods = ['one', 'two', 'three']
methods.forEach(this._addMethod.bind(this))
}
Lib.prototype._addMethod = function (name) {
var self = this
this[name] = function (cb) {
if (!cb) {
self._queue.unshift({name: name})
} else {
self._queue.unshift({name: name})
self._runQueue(cb)
}
return self
}
}
Lib.prototype._runQueue = function (cb) {
var self = this
function run() {
var next = self._queue.pop()
if (next) self['_' + next.name](run)
else cb(null)
}
run()
}
Lib.prototype._one = function (cb) {
process.nextTick(function () {
console.log('one')
cb(null)
})
}
Lib.prototype._two = function (cb) {
process.nextTick(function () {
console.log('two')
cb(null)
})
}
Lib.prototype._three = function (cb) {
process.nextTick(function () {
console.log('three')
cb(null)
})
}
var lib = new Lib()
lib.one()
.two()
.three(function () {
console.log('ALL DONE');
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment