Last active
August 29, 2015 14:15
-
-
Save justmoon/343e3d2211102600e4e2 to your computer and use it in GitHub Desktop.
Control structures: Generators
This file contains hidden or 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 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"); | |
}); |
This file contains hidden or 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
// 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"); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 apromiseWhile
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.