check if function is a generator

后端 未结 12 1411
-上瘾入骨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:25

    this works in node and in firefox:

    var GeneratorFunction = (function*(){yield undefined;}).constructor;
    
    function* test() {
       yield 1;
       yield 2;
    }
    
    console.log(test instanceof GeneratorFunction); // true
    

    jsfiddle

    But it does not work if you bind a generator, for example:

    foo = test.bind(bar); 
    console.log(foo instanceof GeneratorFunction); // false
    

提交回复
热议问题