yield
是 JavaScript 中的一个关键字,主要用于生成器函数(generator function)中。生成器函数是一种特殊类型的函数,可以在执行过程中暂停和恢复。yield
关键字的作用是将函数的执行“暂停”,并返回一个值给调用者。当再次调用该生成器函数时,它会从上次暂停的地方继续执行。
function*
声明的函数。next()
方法。yield
关键字:用于暂停和恢复函数的执行。function* simpleGenerator() {
yield 1;
yield 2;
yield 3;
}
const iterator = simpleGenerator();
console.log(iterator.next()); // { value: 1, done: false }
console.log(iterator.next()); // { value: 2, done: false }
console.log(iterator.next()); // { value: 3, done: false }
console.log(iterator.next()); // { value: undefined, done: true }
Promise
结合使用,简化异步操作。async/await
使用,简化异步代码。原因:可能是由于 yield
后面没有跟任何表达式,或者生成器函数内部逻辑错误。
解决方法:
yield
后面都有有效的表达式。next()
都能正确执行到下一个 yield
。function* fixedGenerator() {
let i = 0;
while (true) {
yield i++;
}
}
const fixedIterator = fixedGenerator();
console.log(fixedIterator.next().value); // 0
console.log(fixedIterator.next().value); // 1
通过这种方式,可以确保生成器函数能够持续且正确地生成值。