js 实现generator
实现 Generator 函数
在 JavaScript 中,Generator 是一种特殊的函数,可以通过 function* 语法定义。Generator 函数可以暂停和恢复执行,通过 yield 关键字实现。
基本语法
定义一个 Generator 函数需要使用 function* 语法,并在函数体内使用 yield 关键字来暂停执行并返回一个值。
function* myGenerator() {
yield 1;
yield 2;
yield 3;
}
调用 Generator 函数不会立即执行函数体,而是返回一个迭代器对象。通过调用迭代器的 next() 方法来逐步执行函数。
const gen = myGenerator();
console.log(gen.next()); // { value: 1, done: false }
console.log(gen.next()); // { value: 2, done: false }
console.log(gen.next()); // { value: 3, done: false }
console.log(gen.next()); // { value: undefined, done: true }
传递参数
可以通过 yield 接收外部传入的值。调用 next() 方法时传入的参数会成为上一个 yield 表达式的返回值。

function* generatorWithParam() {
const a = yield 1;
const b = yield a + 2;
yield b + 3;
}
const gen = generatorWithParam();
console.log(gen.next()); // { value: 1, done: false }
console.log(gen.next(10)); // { value: 12, done: false }
console.log(gen.next(20)); // { value: 23, done: false }
console.log(gen.next()); // { value: undefined, done: true }
提前终止 Generator
可以通过调用 return() 方法提前终止 Generator 函数的执行。
function* infiniteGenerator() {
let i = 0;
while (true) {
yield i++;
}
}
const gen = infiniteGenerator();
console.log(gen.next()); // { value: 0, done: false }
console.log(gen.next()); // { value: 1, done: false }
console.log(gen.return(10)); // { value: 10, done: true }
console.log(gen.next()); // { value: undefined, done: true }
错误处理
可以通过 throw() 方法在 Generator 函数内部抛出错误。

function* errorGenerator() {
try {
yield 1;
yield 2;
} catch (e) {
console.log('Caught error:', e);
}
}
const gen = errorGenerator();
console.log(gen.next()); // { value: 1, done: false }
console.log(gen.throw('Something went wrong')); // Caught error: Something went wrong
console.log(gen.next()); // { value: undefined, done: true }
使用场景
Generator 函数常用于异步编程、惰性求值和生成无限序列等场景。
异步编程示例:
function* fetchUser() {
const user = yield fetch('https://api.example.com/user');
const posts = yield fetch('https://api.example.com/posts');
return { user, posts };
}
无限序列示例:
function* fibonacci() {
let [prev, curr] = [0, 1];
while (true) {
[prev, curr] = [curr, prev + curr];
yield curr;
}
}
const fib = fibonacci();
console.log(fib.next().value); // 1
console.log(fib.next().value); // 2
console.log(fib.next().value); // 3
console.log(fib.next().value); // 5
总结
Generator 函数通过 function* 定义,使用 yield 暂停执行并返回值。调用 Generator 函数返回一个迭代器,通过 next() 方法逐步执行。Generator 适用于异步编程、惰性求值和生成无限序列等场景。






