co-class

Async class methods with coroutines

Usage no npm install needed!

<script type="module">
  import coClass from 'https://cdn.skypack.dev/co-class';
</script>

README

co-class.js

Async class methods with coroutines

Current status

NPM version Build Status Dependency Status Dev dependency Status Greenkeeper badge Coverage Status

What's it for?

In versions of Node without async/await support, co-routines can be used to implement the same functionality using generator functions.

But defining class methods as co-routines is a pain. This module solves that problem.

Usage

If you're on a version of Node that doesn't support async/await, instead of this code:

class MyClass {
  async doSomethingAsync(a, b, c) {
    const res = await Promise.resolve(a * b * c);
    return res;
  }
}

...write this instead:

const coClass = require('co-class');

class MyClass {
  *doSomethingAsync(a, b, c) {
    const res = yield Promise.resolve(a * b * c);
    return res;
  }
}

coClass( MyClass );

How it works

All class methods (both instance methods and static methods) which are generator functions are converted into co-routines.

Co-routines are equivalent to async/await syntax. Co-routine wrapping is performed using co-simple.

super also works as you'd expect for calling methods on a super-class.

Wrapping just instance or static methods

To wrap only static methods:

coClass.static( MyClass );

To wrap on instance methods:

coClass.instance( MyClass );

Calling coClass( MyClass ) is equivalent to calling both the above methods.

Using an alternative wrapper

Just provide it as an option:

const co = require('co-bluebird');
coClass( myClass, { wrapper: co.wrap } );

Tests

Use npm test to run the tests. Use npm run cover to check coverage.

Changelog

See changelog.md

Issues

If you discover a bug, please raise an issue on Github. https://github.com/overlookmotel/co-class/issues

Contribution

Pull requests are very welcome. Please:

  • ensure all tests pass before submitting PR
  • add an entry to changelog
  • add tests for new features
  • document new functionality/API additions in README