Detect Generator Functions with JavaScript

By  on  

In the current JavaScript climate of new syntaxes, features, and using loads of external libraries, it seems harder than ever to be sure what your functions are being given or even what the data represents. Of course, we've come up with Flow and TypeScript to help, but we can't count on those always being available. That's why I like doing my own detection with JavaScript, especially when it comes to function types.

To detect if a function is a generator or async generator function, you can use the following code:

// Sample generator function
function* sampleGenerator() {}
sampleGenerator.constructor.name
// "GeneratorFunction"

async function* sampleGenerator() {}
sampleGenerator.constructor.name
// "AsyncGeneratorFunction"

Coincidentally, you can also detect a regular async function with:

async function asyncThing() {}
asyncThing.constructor.name
// "AsyncFunction"

It's always important to know if the code you're using is sync, async, or a generator, but if you're using external libraries or want to write comprehensive tests, these types of detections may be necessary.

Recent Features

  • By
    Regular Expressions for the Rest of Us

    Sooner or later you'll run across a regular expression. With their cryptic syntax, confusing documentation and massive learning curve, most developers settle for copying and pasting them from StackOverflow and hoping they work. But what if you could decode regular expressions and harness their power? In...

  • By
    5 Awesome New Mozilla Technologies You’ve Never Heard Of

    My trip to Mozilla Summit 2013 was incredible.  I've spent so much time focusing on my project that I had lost sight of all of the great work Mozillians were putting out.  MozSummit provided the perfect reminder of how brilliant my colleagues are and how much...

Incredible Demos

Discussion

    Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!