How to tell function and generator function apart?

Claude Pache claude.pache at
Wed Mar 4 12:20:40 UTC 2015

> Le 3 mars 2015 à 23:19, Guilherme Souza <19gui94 at> a écrit :
> My use case is similar to what Dean has showed:
> My `run()` lib abstraction should work with:
> * a function, with node's done() callback style
> * a generator function, with co's yield promise style [1]
> ```
> // ES5 function
> run(function (data, done) {
>     doSomeAsyncJob(data, done)
> })
> // Generator function
> run(function* (data) {
>     return yield getSomeAsyncJobPromise(data)
> })
> ```
> [1] <>

The hard part is that you should take the "generator function" path for functions that *behave* like generator functions even if they are not, e.g., `gen.bind(null, 'foo')`, where `gen` is a true generator function.

This is how I'd consider to do, if I *really* couldn't ask the user about the nature of the function.

1. At first, don't make any assumption about which code path to take. Let `f` be the function to work with;
2. As a common part of the algorithms for the two cases, call `f(data, done)`, assuming that it is equivalent to `f(data)` if `f` is a generator function;
3. Check whether the result is iterable, i.e, if `typeof result[Symbol.iterator] === 'function'`. If yes, proceed with the "generator function" path. If no, proceed with the "function-with-callback" path.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the es-discuss mailing list