Skip to content

Instantly share code, notes, and snippets.

@narqo
Created June 18, 2014 22:19
Show Gist options
  • Save narqo/c3a1d7d521541bfe57d4 to your computer and use it in GitHub Desktop.
Save narqo/c3a1d7d521541bfe57d4 to your computer and use it in GitHub Desktop.
A silly generator based flow-control example
/** @module cococo */
/**
* A silly control-flow runner
* @param {GeneratorFunction} gen
* @returns {Function}
*/
function cococo(gen) {
return function(done) {
var g = gen();
next();
function next(res) {
var ret = g.next(res);
if(ret.done) return done(ret.value);
if(typeof ret.value === 'function') return ret.value(next);
}
}
}
/** @module lib */
/**
* Some async `foo()`
* @param {String} prefix
* @param {Function} cb callback function
*/
function asyncFoo(prefix, cb) {
var data = prefix + '123';
setTimeout(() => cb(data), 0);
}
/**
* Some async `bar()`
* @param {Function} cb callback function
*/
function asyncBar(fn) {
setTimeout(() => cb('abcabc'), 0);
}
/**
* @module main
* @requires cococo
* @requires thunkify
* @requires lib
*/
var foo = thunkify(asyncFoo),
bar = thunkify(asyncBar);
function *main() {
var a = yield foo('pre://fix');
var b = yield bar();
return a + b;
}
cococo(main)(function(res) {
console.log('->', res);
});
/** @module thunkify */
/**
* A simple thunkifier.
* @see http://en.wikipedia.org/wiki/Thunk
*
* @example
* asyncFoo('prefix', data => console.log(data));
*
* var foo = thunkify(asyncFoo);
* foo('prefix')(data => console.log(data));
*
* @param {Function} asyncFn Some async function
* @param {Object} [ctx]
* @returns {Function} thunkified function
*/
function thunkify(asyncFn, ctx) {
return function() {
var args = arguments.length? Array.prototype.slice.call(arguments, 0) : [];
return function(cb) {
args.push(data => cb(data));
asyncFn.apply(ctx || null, args);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment