copying the co idea but supporting only yielding thunks. run with node >= 0.11.2: `node --harmony myCoExperiment.js`
'use strict'; | |
/*jshint esnext:true */ | |
let log = function(msg) { console.log(msg); }; | |
let now = function() { return Date.now(); }; | |
// emulating co | |
let co = function(fn) { | |
let it = fn(); | |
var cycle = function(loop) { | |
let running = loop; | |
let runOnce = !loop; | |
let out; | |
//log('cycle started with loop: ' + loop); | |
while (running || runOnce) { | |
runOnce = false; | |
out = it.next(); | |
if (out && 'done' in out && 'value' in out) { | |
if (out.done) { | |
running = false; | |
//log('done - stopping cycle due to done'); | |
} | |
else if (typeof out.value === 'function') { | |
running = false; | |
//log('done - stopping cycle due to value being a function (assuming it is a thunk!)'); | |
out.value(cycle); | |
} | |
else { | |
running = true; | |
//log('got other stuff: ' + out.value); | |
} | |
} | |
} | |
}; | |
cycle(true); | |
}; | |
// like co-sleep | |
let sleep = function(ms) { | |
return function(cb) { | |
setTimeout(cb, ms); | |
}; | |
}; | |
co(function *() { | |
log('1) ' + now()); | |
yield sleep(1000); | |
log('2) ' + now()); | |
yield sleep(1000); | |
log('3) ' + now()); | |
yield 2; | |
log('DONE!'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment