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
    I’m an Impostor

    This is the hardest thing I've ever had to write, much less admit to myself.  I've written resignation letters from jobs I've loved, I've ended relationships, I've failed at a host of tasks, and let myself down in my life.  All of those feelings were very...

Incredible Demos

  • By
    Growl-Style Notifications Using MooTools Roar

    When I think of premier MooTools plugin developers, Harald "digitarald" Kirschner is usually one of the first people that come to mind. Harald has built some of MooTools' most popular plugins, including AutoCompleter, FancyUpload, and History Manager. My favorite plugin created...

  • By
    Create a Simple Slideshow Using MooTools

    One excellent way to add dynamism to any website is to implement a slideshow featuring images or sliding content. Of course there are numerous slideshow plugins available but many of them can be overkill if you want to do simple slideshow without controls or events.

Discussion

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