promisify-generator
Convert a Generator into Promise~!
Lightweight utility to promisify a generator, without the need for an entire library like bluebird or co.
#Install
$ npm install --save promisify-generator
#Usage
const pgen = require('promisify-generator');
function * foo() {
let idx = 0;
while (idx <= 5) {
yield idx++;
}
return idx;
}
function * bar() {
let idx = 0;
while (idx <= 5) {
if (idx === 3) {
throw new Error('EQUALS THREE');
}
yield idx++;
}
return idx;
}
const pFoo = pgen(foo);
//=> [Function]
pFoo().then(console.log);
//=> 6
const pBar = pgen(bar);
pBar().then().catch(console.error);
//=> Error: EQUALS THREE
#API
#pgen(fn)
#fn
Type: GeneratorFunction
Returns: Function
The Generator function to promisify.
A normal Function is returned, which invokes a Promise when called. Any arguments passed to this function will be passed to your orginal Generator.
Important: This library does not validate that your
fnis, in fact, aGeneratorFunction!
To manually check if fn is a Generator, you may use the is-generator-function module, or the following snippet:
const isGenerator = fn => fn.constructor.name === 'GeneratorFunction';
#License
MIT © Luke Edwards
See also
clsx(3), @polka/cluster(3), @pwa/cli(3), uvu(3), taskr(3), sockette(3), klona(3), kleur(3), dequal(3), sirv-cli(3)