Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support custom yieldable #310

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
35 changes: 17 additions & 18 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -1,22 +1,21 @@
(The MIT License)
MIT License

Copyright (c) 2014 TJ Holowaychuk <tj@vision-media.ca>
Copyright (c) 2017 Michael Diguet

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
215 changes: 17 additions & 198 deletions Readme.md
Original file line number Diff line number Diff line change
@@ -1,212 +1,31 @@
# co
# cocon

[![Gitter][gitter-image]][gitter-url]
[![NPM version][npm-image]][npm-url]
[![Build status][travis-image]][travis-url]
[![Test coverage][coveralls-image]][coveralls-url]
[![Downloads][downloads-image]][downloads-url]

Generator based control flow goodness for nodejs and the browser,
using promises, letting you write non-blocking code in a nice-ish way.
cocon is an extension of the well known framework co,
allowing to implicitely provide a context that is magically valid during the execution of the generator function.

## Co v4

`co@4.0.0` has been released, which now relies on promises.
It is a stepping stone towards the [async/await proposal](https://github.com/lukehoban/ecmascript-asyncawait).
The primary API change is how `co()` is invoked.
Before, `co` returned a "thunk", which you then called with a callback and optional arguments.
Now, `co()` returns a promise.

```js
co(function* () {
var result = yield Promise.resolve(true);
return result;
}).then(function (value) {
console.log(value);
}, function (err) {
console.error(err.stack);
});
```

If you want to convert a `co`-generator-function into a regular function that returns a promise,
you now use `co.wrap(fn*)`.

```js
var fn = co.wrap(function* (val) {
return yield Promise.resolve(val);
});

fn(true).then(function (val) {

});
```

## Platform Compatibility

`co@4+` requires a `Promise` implementation.
For versions of node `< 0.11` and for many older browsers,
you should/must include your own `Promise` polyfill.

When using node 0.10.x and lower or browsers without generator support,
you must use [gnode](https://github.com/TooTallNate/gnode) and/or [regenerator](http://facebook.github.io/regenerator/).

When using node 0.11.x, you must use the `--harmony-generators`
flag or just `--harmony` to get access to generators.

Node v4+ is supported out of the box, you can use `co` without flags or polyfills.

## Installation

```
$ npm install co
```

## Associated libraries

Any library that returns promises work well with `co`.

- [mz](https://github.com/normalize/mz) - wrap all of node's code libraries as promises.

View the [wiki](https://github.com/visionmedia/co/wiki) for more libraries.

## Examples

```js
var co = require('co');

co(function *(){
// yield any promise
var result = yield Promise.resolve(true);
}).catch(onerror);

co(function *(){
// resolve multiple promises in parallel
var a = Promise.resolve(1);
var b = Promise.resolve(2);
var c = Promise.resolve(3);
var res = yield [a, b, c];
console.log(res);
// => [1, 2, 3]
}).catch(onerror);

// errors can be try/catched
co(function *(){
try {
yield Promise.reject(new Error('boom'));
} catch (err) {
console.error(err.message); // "boom"
}
}).catch(onerror);

function onerror(err) {
// log any uncaught errors
// co will not throw any errors you do not handle!!!
// HANDLE ALL YOUR ERRORS!!!
console.error(err.stack);
}
```

## Yieldables

The `yieldable` objects currently supported are:

- promises
- thunks (functions)
- array (parallel execution)
- objects (parallel execution)
- generators (delegation)
- generator functions (delegation)

Nested `yieldable` objects are supported, meaning you can nest
promises within objects within arrays, and so on!

### Promises

[Read more on promises!](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)

### Thunks

Thunks are functions that only have a single argument, a callback.
Thunk support only remains for backwards compatibility and may
be removed in future versions of `co`.

### Arrays

`yield`ing an array will resolve all the `yieldables` in parallel.

```js
co(function* () {
var res = yield [
Promise.resolve(1),
Promise.resolve(2),
Promise.resolve(3),
];
console.log(res); // => [1, 2, 3]
}).catch(onerror);
```

### Objects

Just like arrays, objects resolve all `yieldable`s in parallel.

```js
co(function* () {
var res = yield {
1: Promise.resolve(1),
2: Promise.resolve(2),
};
console.log(res); // => { 1: 1, 2: 2 }
}).catch(onerror);
```

### Generators and Generator Functions

Any generator or generator function you can pass into `co`
can be yielded as well. This should generally be avoided
as we should be moving towards spec-compliant `Promise`s instead.

## API

### co(fn*).then( val => )

Returns a promise that resolves a generator, generator function,
or any function that returns a generator.

```js
co(function* () {
return yield Promise.resolve(true);
}).then(function (val) {
console.log(val);
}, function (err) {
console.error(err.stack);
});
```

### var fn = co.wrap(fn*)

Convert a generator into a regular function that returns a `Promise`.

```js
var fn = co.wrap(function* (val) {
return yield Promise.resolve(val);
});

fn(true).then(function (val) {

});
```
Before reading this, you will have to understand the following:

https://github.com/tj/co

https://github.com/MichaelDiguet/cPromise

## License

MIT

[npm-image]: https://img.shields.io/npm/v/co.svg?style=flat-square
[npm-url]: https://npmjs.org/package/co
[travis-image]: https://img.shields.io/travis/tj/co.svg?style=flat-square
[travis-url]: https://travis-ci.org/tj/co
[coveralls-image]: https://img.shields.io/coveralls/tj/co.svg?style=flat-square
[coveralls-url]: https://coveralls.io/r/tj/co
[downloads-image]: http://img.shields.io/npm/dm/co.svg?style=flat-square
[downloads-url]: https://npmjs.org/package/co
[npm-image]: https://img.shields.io/npm/v/cocon.svg?style=flat-square
[npm-url]: https://npmjs.org/package/cocon
[travis-image]: https://img.shields.io/travis/MichaelDiguet/cocon.svg?style=flat-square
[travis-url]: https://travis-ci.org/MichaelDiguet/cocon
[coveralls-image]: https://img.shields.io/coveralls/MichaelDiguet/cocon.svg?style=flat-square
[coveralls-url]: https://coveralls.io/r/MichaelDiguet/cocon
[downloads-image]: http://img.shields.io/npm/dm/cocon.svg?style=flat-square
[downloads-url]: https://npmjs.org/package/cocon
[gitter-image]: https://badges.gitter.im/Join%20Chat.svg
[gitter-url]: https://gitter.im/tj/co?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge
[gitter-url]: https://gitter.im/cocon-js?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge
4 changes: 3 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,8 @@ function co(gen) {
if (ret.done) return resolve(ret.value);
var value = toPromise.call(ctx, ret.value);
if (value && isPromise(value)) return value.then(onFulfilled, onRejected);
return onRejected(new TypeError('You may only yield a function, promise, generator, array, or object, '
return onRejected(new TypeError('You may only yield a function, promise, generator, array, '
+ ((ctx && ctx.isYieldable && ctx.toPromise) ? 'object, or custom yieldable, ' : 'or object, ')
+ 'but the following object was passed: "' + String(ret.value) + '"'));
}
});
Expand All @@ -115,6 +116,7 @@ function co(gen) {

function toPromise(obj) {
if (!obj) return obj;
if (this && this.isYieldable && this.toPromise && this.isYieldable(obj)) return this.toPromise(obj);
if (isPromise(obj)) return obj;
if (isGeneratorFunction(obj) || isGenerator(obj)) return co.call(this, obj);
if ('function' == typeof obj) return thunkToPromise.call(this, obj);
Expand Down
14 changes: 11 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "co",
"version": "4.6.0",
"name": "cocon",
"version": "1.0.0",
"description": "generator async control flow goodness",
"keywords": [
"async",
Expand All @@ -27,7 +27,15 @@
"index.js"
],
"license": "MIT",
"repository": "tj/co",
"repository": {
"type": "git",
"url": "git+https://github.com/MichaelDiguet/cocon.git"
},
"author": "Michaël Diguet",
"bugs": {
"url": "https://github.com/MichaelDiguet/cocon/issues"
},
"homepage": "https://github.com/MichaelDiguet/cocon#readme",
"engines": {
"iojs": ">= 1.0.0",
"node": ">= 0.12.0"
Expand Down
41 changes: 41 additions & 0 deletions test/customYieldable.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@

var assert = require('assert');

var co = require('..');

var ctx = {
some: 'thing'
};
ctx.isYieldable = function (obj) {
return 'number' == typeof obj;
};
ctx.toPromise = function (obj) {
return Promise.resolve(obj + 1);
};

describe('yield <custom yieldable>', function () {
it('should throw an error', function () {
return co.call(ctx, function* () {
try {
yield null;
throw new Error('lol');
} catch (err) {
assert(err instanceof TypeError);
assert(~err.message.indexOf('You may only yield'));
assert(~err.message.indexOf('or custom yieldable'));
}
})
})
it('should use the custom toPromise function for custom type', function () {
return co.call(ctx, function* () {
var test = yield 2;
assert(test === 3);
})
})
it('should not use the custom toPromise function for supported type', function () {
return co.call(ctx, function* () {
var test = yield {some: 'thing'};
assert(test.some === 'thing');
})
})
})