javascript - 如何理解javascript生成器?

标签 javascript generator

我有一段代码

function* dataConsumer() {
   console.log('Started');
   console.log(`1. ${yield}`);
   console.log(`2. ${yield}`);
   return 'result';
}

let genObj = dataConsumer();
genObj.next();

运行结果为

Started

我不明白为什么第二个console.log不能输出任何东西。感谢您的帮助。

最佳答案

生成器构建在迭代器之上。要理解生成器,首先需要理解迭代器。查看Documentation .

对于单流,它运行到更近的 yield 并终止函数调用。在它之后,当您再次调用 next 时,它将从它终止的地方继续并再次工作,直到最近的 yield 并且当没有 yields 或它到达 return 语句,它刚刚结束它的调用。

function* dataConsumer() {
  console.log('Started');
  console.log(`1. ${yield}`); // First `next` terminates before yield. Second `next` passes the value and terminates before the next yield.
  console.log(`2. ${yield}`); // Third call continues from the `yield` part and finishes the function, because we have returned
  return 'result';
}

let genObj = dataConsumer();
genObj.next();
genObj.next('yield1'); 
genObj.next('yield2'); 

您还可以将参数传递给next 函数,该函数将放在yield 语句中。此外,next 函数返回一个关于生成器状态的对象,该对象具有属性 valuedone。如果函数调用未完成,它会将 done 返回为 false,最后您可以看到它已设置为 true

function* dataConsumer() {
  console.log('Started');
  const x = yield; 
  console.log(`1. ${x}`);
  console.log(`2. ${yield}`); 
  return 'result';
}

let genObj = dataConsumer();
let result = genObj.next();
console.log(result);

result = genObj.next('x is yield1'); 
console.log(result);

result = genObj.next('yield2'); 
console.log(result);

genObj.next(); // This one has nothing to do

由于您可以在每一步将参数传递给生成器,因此您也可以从 .您需要编写类似于 return something 的内容,只需将 return 替换为 yield

function* dataConsumer() {
  yield 1;
  yield 2;
  yield 3;
}

let genObj = dataConsumer();
let result = genObj.next();
console.log(result);

result = genObj.next(); 
console.log(result);

result = genObj.next(); 
console.log(result);

result = genObj.next(); 
console.log(result);

关于javascript - 如何理解javascript生成器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47693929/

相关文章:

javascript - 单击后从输入中获取值并计算它 - Angular 5

javascript - 如何在 Hexo 中按标签过滤帖子?

python - 检测生成器函数是否为空,否则迭代它

python - 类中生成器中的变量作用域

javascript - 如何从 Promise 内部设置一个在 Promise 外部初始化的变量?

javascript - JS + 改变元素 CSS + 命名 anchor

javascript - 如何让 slider 的MaxValue动态化?

javascript - 输入法所见即所得编辑器不在 mysql 数据库中存储值?

c++ - 是否可以将结构与条件语句完全相同的字符串转换为可以读取和操作的语句?

javascript - 使用生成器函数的输入和输出