Skip to content

Instantly share code, notes, and snippets.

@EyalAr
Created May 9, 2014 07:19
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 EyalAr/f7ddda227e6272238650 to your computer and use it in GitHub Desktop.
Save EyalAr/f7ddda227e6272238650 to your computer and use it in GitHub Desktop.
Code snippets for Javascript generators and asynchronous code presentation. Based on http://eyalarubas.com/javascript-generators-and-callbacks.html
// generate a series of even numbers,
// but be able to to reverse the order of iteration
function * generateEvens(start) {
var dir = 1; // up
if (start % 2 !== 0) start++;
while (true) {
var tmp = yield start;
if (tmp === 'up') dir = 1;
if (tmp === 'down') dir = -1;
start += dir * 2;
}
}
var evens = generateEvens(5);
console.log( evens.next().value ); // 6
console.log( evens.next().value ); // 8
console.log( evens.next('down').value ); // 6
console.log( evens.next().value ); // 4
console.log( evens.next().value ); // 2
console.log( evens.next('up').value ); // 4
console.log( evens.next().value ); // 6
// simulate async database calls with 'getFoo' and 'getBar'.
// retrieve 'foo' and 'bar' and print to console.
var foo, bar;
function getFoo(callback) {
setTimeout(function() {
callback('hello');
}, 200);
}
function getBar(callback) {
setTimeout(function() {
callback('world');
}, 200);
}
getFoo(function(val) {
foo = val
getBar(function(val) {
bar = val;
console.log(foo, bar); // hello world
});
});
// simulate async database calls with 'getFoo' and 'getBar'.
// retrieve 'foo' and 'bar' and print to console.
// try to use a generator to pause execution.
// WILL NOT WORK. SEE '4.async_yield.js'
function getFoo(callback) {
setTimeout(function() {
callback('hello');
}, 200);
}
function getBar(callback) {
setTimeout(function() {
callback('world');
}, 200);
}
function * run (){
var foo = yield getFoo();
var bar = yield getBar();
console.log(foo,bar);
};
run();
// simulate async database calls with 'getFoo' and 'getBar'.
// retrieve 'foo' and 'bar' and print to console.
// use a generator to pause execution.
function getFoo(callback) {
setTimeout(function() {
callback('hello');
}, 200);
}
function getBar(callback) {
setTimeout(function() {
callback('world');
}, 200);
}
function resume(value) {
r.next(value);
}
function * run(resume) {
var foo = yield getFoo(resume);
var bar = yield getBar(resume);
console.log(foo, bar); // hello world
}
var r = run(resume);
r.next(); // start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment