【发布时间】: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