Skip to content

Instantly share code, notes, and snippets.

@JamieMason
Created October 23, 2019 10: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 JamieMason/7deb08607ef765ed33040b877334c9a9 to your computer and use it in GitHub Desktop.
Save JamieMason/7deb08607ef765ed33040b877334c9a9 to your computer and use it in GitHub Desktop.
JavaScript Generators and Async JavaScript Generators
const sleep = secs => new Promise(done => setTimeout(done, secs * 1000));
function* myGenerator() {
const array = [1, 2];
while (array.length) {
yield array.shift();
}
}
const iterable = {
[Symbol.iterator]: myGenerator
};
async function* asyncGenerator() {
const array = [() => sleep(2).then(() => 1), () => sleep(2).then(() => 2)];
while (array.length) {
yield await array.shift()();
}
}
const asyncIterable = {
[Symbol.asyncIterator]: asyncGenerator
};
for (let item of iterable) {
console.log('myGenerator', item);
}
(async function() {
for await (const item of asyncIterable) {
console.log('asyncGenerator', item);
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment