Created
October 23, 2019 10:19
-
-
Save JamieMason/7deb08607ef765ed33040b877334c9a9 to your computer and use it in GitHub Desktop.
JavaScript Generators and Async JavaScript Generators
This file contains 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
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