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());
}
}