Kylee Kylee - 6 months ago 31
Javascript Question

console.log not being called from generator function

I'm using generator functions in javascript for the first time and running in to some interesting problems.


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;

The "TESTING 2" console.log never gets called. It also doesn't raise an error if I don't pass maxDate to the generator function. This must be something about generator's I'm missing.


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

It seems that next needs to be called to run code before the first yield?


In a generator function, the code before the first yield statement gets executed not sooner than the generator proceeds to that point:

let a = function * () {
  yield 2;
  yield 3;

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