Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

next() is not a function unable to use generators in NodeJS

Tags:

node.js

I am using the following code in NodeJS 7.10.0:

function * gen(){
    yield 100;
    yield 200;
    yield 300
}
console.log(gen.next());

and I get this in return:

TypeError: gen.next is not a function
    at Object.<anonymous> (/Files/development/learning/node-bits/generators.js:15:17)
    at Module._compile (module.js:571:32)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.runMain (module.js:605:10)
    at run (bootstrap_node.js:427:7)
    at startup (bootstrap_node.js:151:9)
    at bootstrap_node.js:542:3
like image 276
quinton Avatar asked Sep 06 '25 02:09

quinton


2 Answers

When you call a generator function, its body is not executed. Instead it returns you an iterator object. When you call iterator.next(), body is executed, you get the value and context is maintained.

You can do

let i= gen()
console.log(i.next())

and you will get the desired behaviour.

Refer this: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/function*

like image 129
Krrish Raj Avatar answered Sep 09 '25 00:09

Krrish Raj


You should assign the output of gen to a variable and call next on the returned value:

const out = gen();
console.log(out.next());
console.log(out.next());
console.log(out.next());
console.log(out.next());
like image 36
RickN Avatar answered Sep 08 '25 22:09

RickN