Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs call generator function inside normal function

I have 2 functions: one generator function and one normal one (without *). Generator function (example):

function* generator(i) {
  yield i;
  yield i + 10;
}

and normal function:

function normal(param) {
  var variable = 1;

  // yield generator function 
}

I know that it is impossible to yield inside normal function, but how can I call generator? Do I have to use Promises or smth similar? If it has to be Promise, then how it should look like? I tried to do it this way:

new Promise((resolve) => {
  var result = generator(3);

  Promise.all(result);
});

but this gives me an error

Also how it is working vice versa? For example if I need to call normal function inside generator?

like image 580
Bird Avatar asked May 13 '26 21:05

Bird


2 Answers

You use the next() method on the generator function like this:

function* generator(i) {
  yield i;
  yield i + 10;
}

function higherLevel (){
  let gen = generator(1).next();
  return gen
}

console.log(higherLevel());

This way you can get the next value of yield inside another function.

like image 191
Willem van der Veen Avatar answered May 16 '26 14:05

Willem van der Veen


You may use next function from a GeneratorFunction to go to the next yield statement.

Take a look at the documentation - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*

function* generator(i) {
  yield i;
  yield i + 10;
}

const g = generator(10);
let result = g.next();
while (!result.done) {
    console.log(result.value)
    result = g.next();
}
like image 26
RidgeA Avatar answered May 16 '26 13:05

RidgeA



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!