I played with generators in Nodejs v0.11.2 and I'm wondering how I can check that argument to my function is generator function.
I found this way typeof f === 'function' && Object.getPrototypeOf(f) !== Object.getPrototypeOf(Function)
but I'm not sure if this is good (and working in future) way.
What is your opinion about this issue?
In node 7 you can
instanceof
against the constructors to detect both generator functions and async functions:This works for all circumstances in my tests. A comment above says it doesn't work for named generator function expressions but I'm unable to reproduce:
The only problem is the
.constructor
property of instances can be changed. If someone was really determined to cause you problems they could break it:I checked how koa does it and they use this library: https://github.com/ljharb/is-generator-function.
You can use it like this
Mozilla javascript documentation describes
Function.prototype.isGenerator
method MDN API. Nodejs does not seem to implement it. However if you are willing to limit your code to defining generators withfunction*
only (no returning iterable objects) you can augment it by adding it yourself with a forward compatibility check:this works in node and in firefox:
jsfiddle
But it does not work if you bind a generator, for example:
I'm using this:
We talked about this in the TC39 face-to-face meetings and it is deliberate that we don't expose a way to detect whether a function is a generator or not. The reason is that any function can return an iterable object so it does not matter if it is a function or a generator function.
These two behave identical (minus .throw() but that can be added too)