Skip to content

Generator和Iterator

什么是Generator?

Generator是ES6引入的新概念,它是一种特殊的函数,它可以暂停执行,并在需要时恢复执行。

Generator函数是一个带有*的函数,它的返回值是一个Iterator对象。

Generator函数可以暂停执行,并在需要时恢复执行。它返回一个Iterator对象,可以用for...of循环来遍历。

什么是Iterator?

Iterator是一种接口,它定义了访问集合元素的一种方式。

Iterator对象有两个方法:next()return()

  • next()方法返回一个包含valuedone两个属性的对象,value属性表示当前元素的值,done属性是一个布尔值,表示是否遍历结束。
  • return()方法用于终止遍历。

如何创建Generator函数?

Generator函数是一个带有*的函数,它的返回值是一个Iterator对象。

javascript
function* helloWorld() {
    yield 'hello';
    yield 'world';
}

const hw = helloWorld();

console.log(hw.next().value); // hello
console.log(hw.next().value); // world
console.log(hw.next().value); // undefined

如何使用for...of循环遍历Generator函数?

Generator函数返回的是一个Iterator对象,因此可以使用for...of循环来遍历。

javascript
function* helloWorld() {
    yield 'hello';
    yield 'world';
}

for (let word of helloWorld()) {
    console.log(word);
}
// hello
// world

终止Generator函数的遍历?

Generator函数可以通过调用return()方法来终止遍历。

javascript
function* helloWorld() {
    yield 'hello';
    yield 'world';
}

const hw = helloWorld();

console.log(hw.next().value); // hello
console.log(hw.next().value); // world
console.log(hw.next().value); // undefined

hw.return();

console.log(hw.next().value); // undefined

使用场景

Generator函数的主要用途是用来创建迭代器,可以用来处理异步操作,或者用来生成数据流。

javascript
function* fetchData() {
    const response = yield fetch('https://jsonplaceholder.typicode.com/todos/1');
    const data = yield response.json();
    console.log(data);
}

const generator = fetchData();

const response = generator.next();

response.value.then(data => {
    const next = generator.next(data);
    console.log(next.value);
});

总结

Generator函数是ES6引入的新概念,它是一种特殊的函数,它可以暂停执行,并在需要时恢复执行。

Generator函数返回的是一个Iterator对象,因此可以使用for...of循环来遍历。