Skip to content

Instantly share code, notes, and snippets.

@shuhei
Created July 2, 2014 14:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shuhei/12936bc60f18aadbd26d to your computer and use it in GitHub Desktop.
Save shuhei/12936bc60f18aadbd26d to your computer and use it in GitHub Desktop.
Super simple implementation of something like co
function colike(genFunc) {
var gen = genFunc();
var thunk = gen.next().value;
function done() {
// We don't know the number of arguments.
var err = arguments[0];
var values = Array.prototype.slice.call(arguments, 1);
if (err) {
gen.throw(err);
return;
}
console.log('values', values);
var result = gen.next(values);
if (result.done) {
console.log('Done!');
} else {
console.log('More yields are waiting!');
thunk = result.value;
thunk(done);
}
}
thunk(done);
}
var colike = require('./colike');
colike(function *() {
var a = yield function(callback) {
setTimeout(function() {
callback(null, 1, 2, 3);
}, 100);
};
console.log('a', a);
var b = yield function(callback) {
setTimeout(function() {
callback(null, 'hello', 'world');
}, 100);
};
console.log('b', b);
var c = yield function(callback) {
setTimeout(function() {
callback(new Error('errrrrrrrrror'));
}, 100);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment