如何理解javascript生成器?

时间:2017-12-07 11:20:02

标签: 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无法输出任何内容。谢谢你的帮助。

1 个答案:

答案 0 :(得分:3)

生成器构建在迭代器的顶部。要了解生成器,首先需要了解迭代器。请参阅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);