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 range
2 for (let i = start; i <= end; i++) {
// Wait for delay before yielding
3 await new Promise(r => setTimeout(r, delay));
// Yield the value asynchronously
4 yield i;
5 }
6}
7
// Async function to consume the generator
8async function main() {
// Create generator instance
9 const gen = asyncRange(1, 3, 50);
// Call next() manually: await gives { value, done }; prints 1, then 2
10 console.log((await gen.next()).value);
11 console.log((await gen.next()).value);
// for await...of over a new generator: prints 4 and 5
12 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

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

More JavaScript examples at level 5

← JavaScript typing practice