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
    CSS vs. JS Animation: Which is Faster?

    How is it possible that JavaScript-based animation has secretly always been as fast — or faster — than CSS transitions? And, how is it possible that Adobe and Google consistently release media-rich mobile sites that rival the performance of native apps? This article serves as a point-by-point...

  • By
    Being a Dev Dad

    I get asked loads of questions every day but I'm always surprised that they're rarely questions about code or even tech -- many of the questions I get are more about non-dev stuff like what my office is like, what software I use, and oftentimes...

Incredible Demos

  • By
    Chris Coyier: Some Amazing Work on CodePen III

    I'm back! David asked me to rope up some of my favorite stuff on CodePen again, which I both love doing, and wince at the thought of having to pick so few favorites. I like a ton of stuff on...

  • By
    Create a CSS Cube

    CSS cubes really showcase what CSS has become over the years, evolving from simple color and dimension directives to a language capable of creating deep, creative visuals.  Add animation and you've got something really neat.  Unfortunately each CSS cube tutorial I've read is a bit...

Discussion

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