Last active
April 30, 2024 20:38
-
-
Save jonstoked/2ed72e5b6a259ae9bc558bb4ade92b81 to your computer and use it in GitHub Desktop.
Hello, world!
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
function delayExecution(resolver) { | |
return new Promise((resolve) => setTimeout(() => resolve(resolver), 1000)); | |
} | |
function* messageGenerator() { | |
yield 'H'; | |
yield 'e'; | |
yield 'l'; | |
yield 'l'; | |
yield 'o'; | |
yield ','; | |
yield ' '; | |
yield 'w'; | |
yield 'o'; | |
yield 'r'; | |
yield 'l'; | |
yield 'd'; | |
yield '!'; | |
} | |
async function* asyncMessageIterator(generator) { | |
for (let letter of generator()) { | |
await delayExecution(letter); | |
yield letter; | |
} | |
} | |
function MessageConstructor() { | |
this.parts = []; | |
this[Symbol.asyncIterator] = async function* () { | |
const iterator = asyncMessageIterator(messageGenerator); | |
for await (let part of iterator) { | |
this.parts.push(part); | |
yield part; | |
} | |
}; | |
} | |
async function assembleMessage() { | |
const messageBuilder = new MessageConstructor(); | |
let message = ''; | |
for await (let part of messageBuilder) { | |
message += part; | |
} | |
return message; | |
} | |
assembleMessage().then(console.log); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment