check if function is a generator

后端 未结 12 1416
-上瘾入骨i
-上瘾入骨i 2020-11-29 06:03

I played with generators in Nodejs v0.11.2 and I\'m wondering how I can check that argument to my function is generator function.

I found this way typeof f ===

12条回答
  •  醉话见心
    2020-11-29 06:03

    TJ Holowaychuk's co library has the best function for checking whether something is a generator function. Here is the source code:

    function isGeneratorFunction(obj) {
       var constructor = obj.constructor;
       if (!constructor) return false;
       if ('GeneratorFunction' === constructor.name || 'GeneratorFunction' === constructor.displayName) return true;
       return isGenerator(constructor.prototype);
    }
    

    Reference: https://github.com/tj/co/blob/717b043371ba057cb7a4a2a4e47120d598116ed7/index.js#L221

提交回复
热议问题