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
    How I Stopped WordPress Comment Spam

    I love almost every part of being a tech blogger:  learning, preaching, bantering, researching.  The one part about blogging that I absolutely loathe:  dealing with SPAM comments.  For the past two years, my blog has registered 8,000+ SPAM comments per day.  PER DAY.  Bloating my database...

  • By
    6 Things You Didn’t Know About Firefox OS

    Firefox OS is all over the tech news and for good reason:  Mozilla's finally given web developers the platform that they need to create apps the way they've been creating them for years -- with CSS, HTML, and JavaScript.  Firefox OS has been rapidly improving...

Incredible Demos

  • By
    Display Images as Grayscale with CSS Filters

    CSS filters aren't yet widely supported but they are indeed impressive and a modern need for web imagery.  CSS filters allow you to modify the display of images in a variety of ways, one of those ways being displaying images as grayscale. Doing so requires the...

  • By
    dwImageProtector Plugin for jQuery

    I've always been curious about the jQuery JavaScript library. jQuery has captured the hearts of web designers and developers everywhere and I've always wondered why. I've been told it's easy, which is probably why designers were so quick to adopt it NOT that designers...

Discussion

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