【问题标题】:console.log not being called from generator function没有从生成器函数调用 console.log
【发布时间】:2016-11-24 17:08:16
【问题描述】:

我第一次在 javascript 中使用生成器函数并遇到了一些有趣的问题。

代码:

import moment from 'moment';

export default function recur(quantity, units) {
  console.log('TESTING 1');

  function* recurGenerator(startDate, maxDate) {
    console.log('TESTING 2');

    if (maxDate === undefined) {
      this.throw('Argument maxDate is undefined');
    }

    let nextDate = moment(startDate).clone();
    maxDate = moment(maxDate);

    for (;;) {
      nextDate = moment(nextDate).clone().add(quantity, units);
      if (nextDate.isAfter(maxDate)) yield null;
      yield nextDate;
    }
  }

  return recurGenerator;
}

“TESTING 2”console.log 永远不会被调用。如果我不将 maxDate 传递给生成器函数,它也不会引发错误。这一定是我缺少的生成器。

编辑以显示使用情况

recur(1, 'day')(moment())

好像在第一次yield之前需要调用next来运行代码?

【问题讨论】:

  • 使用生成器的代码在哪里?

标签: javascript


【解决方案1】:

在生成器函数中,第一条yield 语句之前的代码在生成器执行到该点之前执行:

let a = function * () {
  console.log(1);
  yield 2;
  yield 3;
} 

let b = a(); // no console output!
let c = b.next(); // prints 1 to the console
c // { value: 2, done: false }

【讨论】:

  • 我认为这是问题所在。在第一次yield之前需要在返回的生成器对象上调用next来运行代码吗?
  • 是的,必须调用 next 才能继续执行到下一个 yield 语句。在此之前,您可能会认为生成器在函数的第 0 行“暂停”。
猜你喜欢
  • 2019-06-26
  • 2021-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-23
  • 2014-11-23
  • 2016-01-09
  • 2021-09-30
相关资源
最近更新 更多