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?
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.
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With