DevToolBox免费
博客

JavaScript 生成器与迭代器:2026年完整指南

12 分钟作者 DevToolBox

JavaScript 生成器(function*)是可以使用 yield 关键字暂停和恢复执行的特殊函数。它们支持惰性求值、无限序列、双向通信和优雅的异步模式。

生成器基础:function* 和 yield

生成器函数返回一个实现迭代器协议的生成器对象。每个 yield 暂停执行并返回一个值;调用 next() 恢复它。生成器是惰性的——它们按需计算值。

// Generator function syntax: function* with yield
function* counter(start = 0) {
    let i = start;
    while (true) {
        yield i++;    // pauses here, returns i, resumes on next()
    }
}

const gen = counter(1);
console.log(gen.next()); // { value: 1, done: false }
console.log(gen.next()); // { value: 2, done: false }
console.log(gen.next()); // { value: 3, done: false }

// Finite generator
function* range(start, end, step = 1) {
    for (let i = start; i < end; i += step) {
        yield i;
    }
}

// for...of automatically calls .next() and stops at done: true
for (const num of range(0, 10, 2)) {
    console.log(num); // 0, 2, 4, 6, 8
}

// Spread operator works with generators
const nums = [...range(1, 6)]; // [1, 2, 3, 4, 5]

// Destructuring works too
const [a, b, c] = range(10, 20); // a=10, b=11, c=12

双向通信:yield 作为表达式

yield 不仅是 return 语句——它是一个在调用 next(value) 时接收值的表达式。这使得有状态协程和经典 Redux-Saga 模式成为可能。

// Generators support two-way communication
// yield receives values via next(value)
function* calculator() {
    let result = 0;
    while (true) {
        const input = yield result;  // pauses and sends result; receives input
        if (input === null) break;
        result += input;
    }
    return result;
}

const calc = calculator();
calc.next();        // start: { value: 0, done: false }
calc.next(10);      // add 10: { value: 10, done: false }
calc.next(5);       // add 5: { value: 15, done: false }
calc.next(null);    // stop: { value: 15, done: true }

// Generator as stateful iterator
function* idGenerator(prefix = 'id') {
    let id = 1;
    while (true) {
        const reset = yield `${prefix}-${id}`;
        if (reset) {
            id = 1;
        } else {
            id++;
        }
    }
}

const ids = idGenerator('user');
console.log(ids.next().value);       // 'user-1'
console.log(ids.next().value);       // 'user-2'
console.log(ids.next(true).value);   // 'user-1' (reset)
console.log(ids.next().value);       // 'user-2'

yield*:委托给其他可迭代对象

yield* 委托给另一个可迭代对象——无论是生成器、数组、Set、Map 还是字符串。

// yield* — delegate to another iterable
function* innerGen() {
    yield 'a';
    yield 'b';
    yield 'c';
}

function* outerGen() {
    yield 1;
    yield* innerGen();    // delegate: yields 'a', 'b', 'c'
    yield* [4, 5, 6];    // works with any iterable
    yield 7;
}

console.log([...outerGen()]); // [1, 'a', 'b', 'c', 4, 5, 6, 7]

// Practical: flatten nested arrays
function* flatten(arr) {
    for (const item of arr) {
        if (Array.isArray(item)) {
            yield* flatten(item); // recursive delegation
        } else {
            yield item;
        }
    }
}

const nested = [1, [2, [3, 4], 5], [6, 7]];
console.log([...flatten(nested)]); // [1, 2, 3, 4, 5, 6, 7]

// Tree traversal with yield*
function* walkTree(node) {
    yield node.value;
    for (const child of node.children ?? []) {
        yield* walkTree(child); // depth-first traversal
    }
}

异步生成器:流式数据

异步生成器(async function*)将生成器与 async/await 结合。非常适合流式 API——数据到达时处理,而不是等待所有内容加载完毕。

// Async generators: async function* with yield
async function* streamLines(url) {
    const response = await fetch(url);
    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    let buffer = '';

    while (true) {
        const { done, value } = await reader.read();
        if (done) {
            if (buffer) yield buffer;
            break;
        }
        buffer += decoder.decode(value, { stream: true });
        const lines = buffer.split('\n');
        buffer = lines.pop() ?? '';
        for (const line of lines) {
            yield line;   // yield each complete line
        }
    }
}

// Usage with for await...of
async function processCSV(url) {
    let lineNumber = 0;
    for await (const line of streamLines(url)) {
        lineNumber++;
        if (lineNumber === 1) continue; // skip header
        const [name, score] = line.split(',');
        console.log(`${name}: ${score}`);
    }
}

// SSE (Server-Sent Events) as async generator
async function* sseStream(url) {
    const response = await fetch(url);
    const reader = response.body.getReader();
    const decoder = new TextDecoder();

    for await (const chunk of readChunks(reader)) {
        const text = decoder.decode(chunk);
        for (const line of text.split('\n')) {
            if (line.startsWith('data: ')) {
                yield JSON.parse(line.slice(6));
            }
        }
    }
}

实际应用场景

生成器支持惰性管道,只处理所需的数据。结合 filter()、map() 和 take() 生成器,可以组合数据转换而不创建中间数组。

// Real-world: infinite scroll with generator
function* paginator(fetchPage) {
    let page = 1;
    let hasMore = true;

    while (hasMore) {
        const { items, totalPages } = yield fetchPage(page);
        hasMore = page < totalPages;
        page++;
    }
}

// Lazy pipeline with generators
function* map(iterable, fn) {
    for (const item of iterable) {
        yield fn(item);
    }
}

function* filter(iterable, predicate) {
    for (const item of iterable) {
        if (predicate(item)) yield item;
    }
}

function* take(iterable, n) {
    let count = 0;
    for (const item of iterable) {
        if (count++ >= n) break;
        yield item;
    }
}

// Lazy pipeline — no intermediate arrays created!
const first10EvenSquares = [
    ...take(
        filter(
            map(range(1, Infinity), x => x * x),
            x => x % 2 === 0
        ),
        10
    )
];
// [4, 16, 36, 64, 100, 144, 196, 256, 324, 400]

// Observable-like: cancelable async iteration
async function* withTimeout(asyncIterable, timeoutMs) {
    const timeout = setTimeout(() => {
        throw new Error('Stream timed out');
    }, timeoutMs);
    try {
        for await (const item of asyncIterable) {
            yield item;
        }
    } finally {
        clearTimeout(timeout);
    }
}

生成器 vs 其他方案

FeatureGeneratorasync/awaitPromiseObservable
Infinite sequencesPerfectNoNoYes
Lazy evaluationYes (pull-based)NoNoYes (push)
BackpressureNatural (pull)NoNoYes
Streaming asyncasync function*NoNoYes (RxJS)
Two-way commsyield expressionNoNoNo
Browser supportES2015+ (all)ES2017+ES2015+Requires RxJS

最佳实践

  • 对惰性序列和无限数据源使用生成器。对返回单个值的一次性异步操作使用 async/await。
  • 使用 return 从生成器提前退出以设置 done: true。使用 try/finally 在生成器被放弃时进行清理。
  • 异步生成器非常适合流式 HTTP 响应、SSE 流和 WebSocket 消息处理。
  • 将可复用的管道助手(map、filter、take、zip)构建为生成器函数,以实现内存高效的数据转换。
  • TypeScript:用 Generator<YieldType, ReturnType, NextType> 注解生成器返回类型以获得完整类型安全。

常见问题

生成器和迭代器有什么区别?

迭代器是任何具有返回 { value, done } 的 next() 方法的对象。生成器是自动创建和管理迭代器的函数。所有生成器都是迭代器,但并非所有迭代器都是生成器。

生成器可以替代 async/await 吗?

曾经可以——在 async/await 出现之前,co() 等库使用生成器模拟异步代码。今天,async/await 对于一次性 Promise 更简单。但异步生成器在流式处理方面很出色。

什么是迭代器协议?

实现迭代器协议的对象有一个 next() 方法,返回 { value: T, done: boolean }。可迭代对象有一个 [Symbol.iterator]() 方法返回迭代器。生成器对象两者都实现。

生成器适合用于 Redux-Saga 吗?

是的——Redux-Saga 大量使用生成器。Sagas 是 yield 效果描述符(call、put、take、fork)的生成器函数。

如何取消生成器或异步生成器?

调用 generator.return(value) 强制结束它。对于在 for await...of 中使用的异步生成器,从循环中 break 或 return 会自动调用生成器的 return() 方法。

相关工具

𝕏 Twitterin LinkedIn
这篇文章有帮助吗?

保持更新

获取每周开发技巧和新工具通知。

无垃圾邮件,随时退订。

试试这些相关工具

{ }JSON FormatterB→Base64 Encode Online

相关文章

JavaScript 闭包详解:作用域、内存与实战模式

2026年JavaScript闭包深度指南:词法作用域、闭包内存影响、记忆化、模块模式与柯里化实战。

TypeScript 类型守卫:运行时类型检查完全指南

掌握 TypeScript 类型守卫:typeof、instanceof、in、自定义类型守卫和可辨识联合。

React Query 模式 2026:TanStack Query 数据获取、缓存与变更

2026年精通React Query (TanStack Query) 模式:useQuery、useMutation、乐观更新与服务器状态管理。