Created
July 2, 2014 14:55
-
-
Save shuhei/12936bc60f18aadbd26d to your computer and use it in GitHub Desktop.
Super simple implementation of something like co
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
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); | |
} |
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
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