Last active
August 29, 2015 14:07
-
-
Save gimenete/09c7933ef017a3ac8d4f to your computer and use it in GitHub Desktop.
Promises-like control flow without promises
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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