promisify-generator

1.0.0 • Public • Published

promisify-generator Build Status

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 fn is, in fact, a GeneratorFunction!

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

Versions

Current Tags

  • Version
    Downloads (Last 7 Days)
    • Tag
  • 1.0.0
    2
    • latest

Version History

  • Version
    Downloads (Last 7 Days)
    • Published
  • 1.0.0
    2

Package Sidebar

Install

npm i promisify-generator

Weekly Downloads

2

Version

1.0.0

License

MIT

Last publish

Collaborators

  • lukeed