Async Generator in JavaScript
Level 5355 keystrokes
Async generators combine async/await with generators for asynchronous iteration.
JavaScript code
// Async generator function using async function*1async function* asyncRange(start, end, delay) { // Loop through the range2 for (let i = start; i <= end; i++) { // Wait for delay before yielding3 await new Promise(r => setTimeout(r, delay)); // Yield the value asynchronously4 yield i;5 }6}7 // Async function to consume the generator8async function main() { // Create generator instance9 const gen = asyncRange(1, 3, 50); // Call next() manually: await gives { value, done }; prints 1, then 210 console.log((await gen.next()).value);11 console.log((await gen.next()).value); // for await...of over a new generator: prints 4 and 512 for await (const n of asyncRange(4, 5, 50)) {13 console.log(n);14 }15}16 // Start main (it returns a Promise)17main();Output
1 2 4 5
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this JavaScript code and how often they appear.
(× 16)× 16;× 9,× 7.× 7{× 4}× 4=× 4+× 2*× 1