簡體   English   中英

未從生成器函數調用console.log

[英]console.log not being called from generator function

我第一次在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())

似乎需要在第一次產生前調用next來運行代碼?

在生成器函數中,第一個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 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM