Skip to content

Instantly share code, notes, and snippets.

@gimenete
Last active August 29, 2015 14:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gimenete/09c7933ef017a3ac8d4f to your computer and use it in GitHub Desktop.
Save gimenete/09c7933ef017a3ac8d4f to your computer and use it in GitHub Desktop.
Promises-like control flow without promises
module.exports = function(f) {
var pro = {}
var chain = []
var end = null
function next() {
var f = chain.shift()
if (!f) {
end.apply(null, arguments)
} else {
var args = Array.prototype.slice.call(arguments)
var err = args.shift()
if (err) {
end.call(null, err)
} else {
// remove arguments if needed
if (args.length >= f.length) {
args = args.splice(0, f.length - 1)
} else {
// add arguments if needed
for (var i = args.length; i < f.length - 1; i++) {
args.push(void 0)
}
}
args.push(next)
f.apply(null, args)
}
}
}
pro.then = function(f) {
chain.push(f)
return pro
}
pro.end = function(f) {
end = f
next()
}
return pro.then(f)
}
if (module.id === require.main.id) {
var chain = module.exports
// example
chain(function(callback) {
callback(null, 'hello', 'world')
})
.then(function(a, b, c, callback) {
callback(null, { foo: a })
})
.end(function(err, obj) {
if (err) return console.log('err', err)
console.dir(obj)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment