-1

Heyo! I'm playing with function*'s and yield's. I've noticed that (In NodeJS) anyway, when I try to call yield when I'm not within a function*, yield is undefined. Though yield is keyword so I can't exactly check if yield === undefined.

So what I am asking is, how can I tell if my code is currently running through a function*?

ARitz Cracker
  • 77
  • 1
  • 4
  • 1
    You'll get a lot more help to show the code you're using that is giving you your `yield === undefined`. – krillgar Mar 23 '17 at 14:48
  • Possible duplicate of [How to check if a variable is a generator function? (e.g function\* yield)](http://stackoverflow.com/questions/34103051/how-to-check-if-a-variable-is-a-generator-function-e-g-function-yield) – Felipe Skinner Mar 23 '17 at 15:25
  • All you need to do is to look at your code and check whether the enclosing function has a `*` on it. There is no way, and no need, to check for this dynamically in code. – Bergi Aug 08 '20 at 15:00

2 Answers2

0

Since generators aren't constructable, you can try using new GeneratorFunction(), and it will throw a TypeError in case it's a generator function.

function* gen() {
  yield 1;
}

function fn() {
  return 1;
}

function isGenerator(fn) {
  try {
    new fn();
    return false;
  } catch (err) {
    return true;
  }
}

console.log(isGenerator(gen)); // true
console.log(isGenerator(fn)); // false

You can also check for Object.getPrototypeOf(gen), and it will return a Generator constructor. Then you can do for example:

console.log(Object.getPrototypeOf(gen).prototype[Symbol.toStringTag]); // Generator
Edmundo Santos
  • 8,006
  • 3
  • 28
  • 38
0

To find out whether you are currently within a GeneratorFunction, you could check the function's constructor:

function* generator() {
  
  // Recommended:
  console.log(Object.getPrototypeOf(generator).constructor === Object.getPrototypeOf(function*(){}).constructor);
  
  // Deprecated:
  console.log(Object.getPrototypeOf(arguments.callee).constructor === Object.getPrototypeOf(function*(){}).constructor);
}

generator().next();
le_m
  • 19,302
  • 9
  • 64
  • 74