Skip to content

Instantly share code, notes, and snippets.

@justmoon
Last active August 29, 2015 14:15
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 justmoon/343e3d2211102600e4e2 to your computer and use it in GitHub Desktop.
Save justmoon/343e3d2211102600e4e2 to your computer and use it in GitHub Desktop.
Control structures: Generators
var sleep = require('co-sleep');
var co = require('co');
co(function *() {
var sum = 0,
stop = 10;
while (sum < stop) {
// Arbitrary 250ms async method to simulate async process
// In real usage it could just be a normal async event that
// returns a Promise.
yield sleep(250);
sum++;
// Print out the sum thus far to show progress
console.log(sum);
}
console.log("Done");
});
// From: http://blog.victorquinn.com/javascript-promise-while-loop
// And below is a sample usage of this promiseWhile function
var sum = 0,
stop = 10;
promiseWhile(function() {
// Condition for stopping
return sum < stop;
}, function() {
// Action to run, should return a promise
return new Promise(function(resolve, reject) {
// Arbitrary 250ms async method to simulate async process
// In real usage it could just be a normal async event that
// returns a Promise.
setTimeout(function() {
sum++;
// Print out the sum thus far to show progress
console.log(sum);
resolve();
}, 250);
});
}).then(function() {
// Notice we can chain it because it's a Promise,
// this will run after completion of the promiseWhile Promise!
console.log("Done");
});
@justmoon
Copy link
Author

Quick comparison between promises and promises with generators. Note how generators make JavaScript control structures available again in asynchronous code. We can use while instead of having to use a promiseWhile function or library.

The promise example is a real example from a highly search engine ranking blog post on the subject. The generator version is a port I wrote. To keep it sort of fair in terms of code length, I kept any comments related to functionality and only stripped comments related to explaining the non-native control structure. I.e. comments you arguably no longer need.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment