Ad

IsGenerator Implementation

- 1 answer

I previously relied on the following definition of how to detect a generator:

function isGenerator(func) {
    return func instanceof Function && func.constructor.name === 'GeneratorFunction';
}

Since then however I came across various other verifications, including checks for next and throw functions on the prototype.

Is there a way to implement isGenerator function to be considered comprehensive within the realm of NodeJS 0.10 - 5.x?

The application in which I intend to use is to pick up any generator (or even iterator), and wrap it up into a promise that would make use of functions next and throw.

For that I'm using a modified example from here:

/////////////////////////////////
// Generator-to-Promise adapter;
function asyncAdapter(generator) {
    return function () {
        var g = generator.apply(this, arguments);

        function handle(result) {
            if (result.done) {
                return Promise.resolve(result.value);
            }
            return Promise.resolve(result.value)
                .then(function (res) {
                    return handle(g.next(res));
                }, function (err) {
                    return handle(g.throw(err));
                });
        }

        return handle(g.next());
    }
}
Ad

Answer

I previously relied on the following definition of how to detect a generator […]

That doesn't detect generators, it detects generator functions. And you should not rely on such a thing, as every function can return a generator.

Is there a way to implement isGeneratorFunction to be considered comprehensive within the realm of NodeJS 0.10 - 5.x?

Yes, there are a few, next to the .constructor.name approach you've shown one can also use instanceof or .toString().

The application in which I intend to use is to pick up any generator (or even iterator)

Don't do this by magic. Just let the user decide whether they want to use generators, and let them call your function explicitly in that case.

Ad
source: stackoverflow.com
Ad