Async Iterator in JavaScript

Level 5266 keystrokes

Implements an async generator that yields values with delays, consumed with for await...of.

JavaScript code

// async function* declares an async generator function
// Combines async/await with generator functionality
1async function* asyncNumbers(start, end) {
// Loop from start to end
2 for (let i = start; i <= end; i++) {
// Await a delay before yielding each value
// Simulates async operations like API calls
3 await new Promise(r => setTimeout(r, 50));
// yield pauses and returns the current number
4 yield i;
5 }
6}
7
// IIFE (Immediately Invoked Function Expression) to use await
8(async () => {
// Array to collect results
9 const numbers = [];
// for await...of iterates over async generators
// Each iteration waits for the next yielded value
10 for await (const num of asyncNumbers(1, 5)) {
11 numbers.push(num);
12 }
// Output: [1, 2, 3, 4, 5]
13 console.log(numbers);
14})();

Output

[ 1, 2, 3, 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.

  • (× 11
  • )× 11
  • ;× 8
  • =× 5
  • {× 4
  • }× 4
  • ,× 3
  • .× 2
  • +× 2
  • >× 2

More JavaScript examples at level 5

← JavaScript typing practice