Building Your Learning Module...
Getting things ready for you!
Find videos you like?
Save to resource drawer for future reference!
Generators let you pause and resume functions with yield. Async iterators let you iterate over promises one at a time. Perfect for handling streams, paginated APIs, and lazy data loading!
Functions that can pause execution with yield and resume later. Returns an iterator.
Iterate over async data (promises) using for await...of. Perfect for streams!
See how generators pause and resume execution
<div style="max-width: 700px; margin: 0 auto; font-family: 'Segoe UI', sans-serif;">
<div style="background: linear-gradient(135deg, #a855f7 0%, #d946ef 100%); padding: 40px; border-radius: 16px; text-align: center; box-shadow: 0 10px 30px rgba(168, 85, 247, 0.3);">
<h2 style="color: white; margin: 0 0 12px 0; font-size: 28px; font-weight: 700;">⚡ Generator Demo</h2>
<p style="color: rgba(255, 255, 255, 0.9); margin: 0 0 30px 0; font-size: 15px;">Click to get next value from generator</p>
<button id="nextBtn" style="padding: 16px 40px; background: white; color: #a855f7; border: none; border-radius: 12px; cursor: pointer; font-weight: 700; font-size: 18px; box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2); transition: all 0.3s;">
▶️ Get Next Value
</button>
<div id="output" style="margin-top: 30px; padding: 24px; background: rgba(255, 255, 255, 0.95); border-radius: 12px; min-height: 100px; backdrop-filter: blur(10px);"></div>
</div>
</div>Loading preview...
// Define generator with function*
function* countToThree() {
yield 1; // Pause and return 1
yield 2; // Pause and return 2
yield 3; // Pause and return 3
}
// Create iterator
const counter = countToThree();
console.log(counter.next()); // { value: 1, done: false }
console.log(counter.next()); // { value: 2, done: false }
console.log(counter.next()); // { value: 3, done: false }
console.log(counter.next()); // { value: undefined, done: true }
// 🎯 Or use for...of
for (const num of countToThree()) {
console.log(num); // 1, 2, 3
}// Generate infinite Fibonacci numbers
function* fibonacci() {
let [prev, curr] = [0, 1];
while (true) {
yield curr;
[prev, curr] = [curr, prev + curr];
}
}
const fib = fibonacci();
console.log(fib.next().value); // 1
console.log(fib.next().value); // 1
console.log(fib.next().value); // 2
console.log(fib.next().value); // 3
console.log(fib.next().value); // 5
// Get first 5 fibonacci numbers
const firstFive = [];
const gen = fibonacci();
for (let i = 0; i < 5; i++) {
firstFive.push(gen.next().value);
}
console.log(firstFive); // [1, 1, 2, 3, 5]// Create an async iterable object
const asyncIterable = {
async *[Symbol.asyncIterator]() {
yield await Promise.resolve(1);
yield await Promise.resolve(2);
yield await Promise.resolve(3);
}
};
// Consume with for await...of
async function consume() {
for await (const value of asyncIterable) {
console.log(value); // 1, 2, 3
}
}
consume();
// 🎯 Works with any object that has [Symbol.asyncIterator]// Custom async iterator
const delayedNumbers = {
async *[Symbol.asyncIterator]() {
for (let i = 1; i <= 5; i++) {
// Simulate API delay
await new Promise(resolve => setTimeout(resolve, 1000));
yield i;
}
}
};
// Use it
async function processNumbers() {
console.log('⏳ Starting...');
for await (const num of delayedNumbers) {
console.log(`📦 Got: ${num}`);
}
console.log('✅ Complete!');
}
processNumbers();
// Output (with 1s delays between each):
// ⏳ Starting...
// 📦 Got: 1
// 📦 Got: 2
// 📦 Got: 3
// 📦 Got: 4
// 📦 Got: 5
// ✅ Complete!// Async generator for paginated data
async function* fetchPages(url) {
let page = 1;
let hasMore = true;
while (hasMore) {
// Fetch current page
const response = await fetch(`${url}?page=${page}`);
const data = await response.json();
// Yield data for this page
yield data.items;
// Check if more pages
hasMore = data.hasNextPage;
page++;
}
}
// Use with for await...of
async function loadAllUsers() {
for await (const users of fetchPages('/api/users')) {
console.log('Got page:', users);
// Process users...
}
console.log('All pages loaded!');
}
loadAllUsers();// Stream data with delays
async function* dataStream() {
for (let i = 1; i <= 5; i++) {
// Simulate API delay
await new Promise(resolve => setTimeout(resolve, 1000));
yield { id: i, timestamp: Date.now() };
}
}
// Consume stream
async function processStream() {
console.log('⏳ Starting stream...');
for await (const data of dataStream()) {
console.log('📦 Received:', data);
}
console.log('✅ Stream complete!');
}
processStream();
// Output (with 1s delays):
// ⏳ Starting stream...
// 📦 Received: { id: 1, timestamp: ... }
// 📦 Received: { id: 2, timestamp: ... }
// ...
// ✅ Stream complete!Generate values only when needed. Memory efficient for large datasets!
Fetch pages one at a time without loading everything at once
Process streams of data (WebSockets, file reading, real-time updates)
Generate infinite sequences (IDs, timestamps, math sequences)
function* gen() {
yield 1;
yield 2;
}
for (const val of gen()) {
console.log(val);
}async function* gen() {
yield await fetch('/1');
yield await fetch('/2');
}
for await (const val of gen()) {
console.log(val);
}yield pauses execution, .next() resumes
Generate values only when needed - memory efficient!
for await...of for promises
APIs, pagination, real-time data, file reading