Skip to content

Instantly share code, notes, and snippets.

@gnepud
Created February 9, 2017 11:36
Show Gist options
  • Save gnepud/f21486a5cdbcd84806b059af2ff4c9e2 to your computer and use it in GitHub Desktop.
Save gnepud/f21486a5cdbcd84806b059af2ff4c9e2 to your computer and use it in GitHub Desktop.
Example: User Promise and Generator for handle async in Javascript
function run(generator, res) {
const ret = generator.next(res);
if (ret.done) return;
ret.value.then(function (res) {
run(generator, res);
});
}
let count = 1;
function tick(time) {
return new Promise(resolve => {
setTimeout(() => {
console.log('tick %s after %s ms', count++, time);
resolve();
}, time);
});
}
function* main() {
console.log('start run...');
yield tick(500);
yield tick(1000);
yield tick(2000);
}
run(main());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment