{"id":17128049,"url":"https://github.com/novacrazy/bluebird-co","last_synced_at":"2025-08-21T12:31:11.073Z","repository":{"id":34818860,"uuid":"38805835","full_name":"novacrazy/bluebird-co","owner":"novacrazy","description":"A set of high performance yield handlers for Bluebird coroutines","archived":false,"fork":false,"pushed_at":"2016-10-26T05:50:38.000Z","size":240,"stargazers_count":76,"open_issues_count":0,"forks_count":3,"subscribers_count":3,"default_branch":"master","last_synced_at":"2024-05-13T17:26:40.626Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/novacrazy.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2015-07-09T07:47:13.000Z","updated_at":"2022-05-30T02:14:12.000Z","dependencies_parsed_at":"2022-08-03T22:45:23.580Z","dependency_job_id":null,"html_url":"https://github.com/novacrazy/bluebird-co","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/novacrazy%2Fbluebird-co","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/novacrazy%2Fbluebird-co/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/novacrazy%2Fbluebird-co/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/novacrazy%2Fbluebird-co/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/novacrazy","download_url":"https://codeload.github.com/novacrazy/bluebird-co/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":230511483,"owners_count":18237658,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-10-14T19:06:07.910Z","updated_at":"2024-12-19T23:15:34.751Z","avatar_url":"https://github.com/novacrazy.png","language":"JavaScript","funding_links":[],"categories":["Packages","包"],"sub_categories":["Control flow Generators","Control flow"],"readme":"bluebird-co\n=============\n[![NPM Version][npm-image]][npm-url]\n[![NPM Downloads][downloads-image]][npm-url]\n[![MIT License][license-image]][npm-url]\n[![Build Status][build-image]][build-link]\n\nA set of high performance yield handlers for Bluebird coroutines.\n\n# Description\nbluebird-co is a reimplementation of [tj/co](https://github.com/tj/co) generator coroutines using [bluebird](https://github.com/petkaantonov/bluebird), [Bluebird.coroutine](http://bluebirdjs.com/docs/api/promise.coroutine.html) and [Bluebird.coroutine.addYieldHandler](http://bluebirdjs.com/docs/api/promise.coroutine.addyieldhandler.html) to insert a yield handler that can transform all the same yieldable value types as tj/co and more.\n\n[Yieldable Types](#yieldable-types) include arrays of promises, objects with promises as properties, thunks, other generators, and even ES6 iterables. Plus bluebird-co allows for additional yield handlers to be added that work together in combination with all the existing yield handlers.\n\nCombined with [Babel's `async-to-module-method`](http://babeljs.io/docs/plugins/transform-async-to-module-method/) (or `bluebirdCoroutines` in Babel 5) transformer, you can write easy and comprehensive `async/await` functions.\n\n# Quickstart\n\nTo install:\n`npm install bluebird-co`\n\nEnsure Bluebird is installed:\n`npm install bluebird@3`\n\n# Performance\nSqueezing the most performance out of every asynchronous operation was a high priority for bluebird-co, and as a result it is much faster than tj/co in essentially every scenario.\n\n[See here for detailed benchmarks](https://github.com/novacrazy/bluebird-co/tree/master/benchmark)\n\n# Usage\nbluebird-co includes Bluebird as a [peer dependency](https://docs.npmjs.com/files/package.json#peerdependencies) so that it will use any already installed instance of Bluebird, making it easier to bootstrap and integrate.\n\nUsing automatic bootstrapping:\n```javascript\nrequire('bluebird-co');\n```\n\nand done.\n\nAlternatively, manually adding the yield handler to Bluebird:\n\n```javascript\nvar Promise     = require('bluebird'),\n    bluebird_co = require('bluebird-co/manual');\n\nPromise.coroutine.addYieldHandler(bluebird_co.toPromise);\n\nvar fn = Promise.coroutine(function*(){\n    //do stuff\n});\n\nfn().then(...);\n```\n\nIn the automatic bootstrapping version, it actually executes the same first four lines of code as above to add the yield handler. Bluebird-co provides manual bootstrapping for control over the process if desired.\n\n### Usage with Babel 6:\n\nBabel 6 provides the [transform-async-to-module-method](http://babeljs.io/docs/plugins/transform-async-to-module-method/) plugin which can pass a generator to a function to convert it to an asynchronous coroutine. Using bluebird-co instead of the default Bluebird install will automatically bootstrap the yield handler while remaining completely transparent.\n\n**.babelrc file**\n```javascript\n{\n    \"plugins\": [\n        [\"transform-async-to-module-method\", {\n            \"module\": \"bluebird-co\",\n            \"method\": \"coroutine\"\n        }]\n    ]\n}\n```\n\n**ES7 file to be transformed**\n```javascript\nasync function fn() {\n    //do stuff\n}\n\nfn().then(...);\n```\n\n# Example coroutines\n**Note**: bluebird-co has to be added to Bluebird via automatic bootstrapping or manual addition before these snippets can work.\n\n```javascript\nvar Promise = require('bluebird');\nvar fs = Promise.promisifyAll(require('fs'));\n\nvar myAsyncFunction = Promise.coroutine(function*() {\n    var results = yield [Promise.delay( 10 ).return( 42 ),\n                         readFileAsync( 'index.js', 'utf-8' ),\n                         [1, Promise.resolve( 12 )]];\n\n    console.log(results); //[42, \"somefile contents\", [1, 12]]\n});\n\nmyAsyncFunction().then(...);\n```\n\n### ES7 version\n```javascript\nimport Promise from 'bluebird';\nimport {readFile} from 'fs';\n\nlet readFileAsync = Promise.promisify(readFile);\n\nasync function myAsyncFunction() {\n    let results = await [Promise.delay( 10 ).return( 42 ),\n                         readFileAsync( 'index.js', 'utf-8' ),\n                         [1, Promise.resolve( 12 )]];\n\n    console.log(results); //[42, \"somefile contents\", [1, 12]]\n}\n\nmyAsyncFunction().then(...);\n```\n\n### tj/co drop-in replacement\n```javascript\nimport {co} from 'bluebird-co';\n\nco(...);\nco.wrap(...);\n```\n\n##### For more examples, see the [tj/co README](https://github.com/tj/co/blob/master/Readme.md#examples) and the [Bluebird Coroutines API](http://bluebirdjs.com/docs/api/promise.coroutine.html).\n\n\n# Yieldable Types\n\n* Promises\n* Arrays\n* Objects\n* Generators and GeneratorFunctions\n* Iterables (like `new Set([1, 2, 3]).values()`)\n* Functions (as Thunks)\n* Custom data types via [`.addYieldHandler(fn)`#addyieldhandlerfn--function\n* Any combination or nesting of the above.\n\n# Custom yieldable types\nIt may become desirable to add custom yield handling for types not listed above based on the needs of a certain application. To make this easy, bluebird-co provides an analogue to Bluebird's [Bluebird.coroutine.addYieldHandler](http://bluebirdjs.com/docs/api/promise.coroutine.addyieldhandler.html) that works together in combination with the above yield handlers.\n\nTo do this, bluebird-co provides the [`.coroutine.addYieldHandler(fn)`](#addyieldhandlerfn--function) function, or just [`.addYieldHandler(fn)`](#addyieldhandlerfn--function) for short. The first is for strict compatibility with Bluebird.\n\nExample of automatically fetching model data by yielding the model instance:\n```javascript\nimport {coroutine} from 'bluebird-co';\n\nclass MyModel {\n    async fetch() {\n        //do stuff\n        return data;\n    }\n}\n\ncoroutine.addYieldHandler(function(value) {\n    if(value instanceof MyModel) {\n        return value.fetch();\n    }\n});\n\nasync function test() {\n    let model = new MyModel();\n\n    let data = await model; //calls model.fetch() and waits on it.\n}\n```\n\nAdditionally, you can even access the array of yield handlers manually if you ever need to remove one, like so:\n```javascript\nconsole.log(coroutine.yieldHandlers); //array of functions\n```\n\n#### Caveats:\n\nAlthough this works for most classes and even null, it will **NOT** work if the class inherits from `Object` or if `Object` is in the prototype chain for the value's constructor. If it inherits from `Object`, it will be considered an `Object` instance and processed like any other object. Values without any `constructor` property will be considered an `Object`, as well.\n\n# API\n\nAll functions and properties listed below are exported by the `bluebird-co` module.\n\n-----\n##### `.toPromise(value : any)` -\u003e `Promise\u003cany\u003e | any`\n\n`toPromise` is the central function of bluebird-co. It takes any of the supported yieldable types (and those added via [`.addYieldHandler`](#addyieldhandlerfn--function)), and attempts to convert it to a Promise. Any Promises within the value are resolved before the returned Promise resolves.\n\nIn the event that the given value cannot be transformed into a Promise, like when it is not in the possible yieldable types, the original value is returned. When used in conjunction with Bluebird coroutines, Bluebird will throw an error because the value is not a Promise instance.\n\n-----\n##### `.addYieldHandler(fn : Function)`\n**alias**: `.coroutine.addYieldHandler(fn : Function)`\n\nVery similar to [Bluebird.coroutine.addYieldHandler](http://bluebirdjs.com/docs/api/promise.coroutine.addyieldhandler.html), `.addYieldHandler` allows custom types to be processed by bluebird-co in conjunction with any other yieldable types, even other custom yield handlers. This includes nested yieldable types.\n\nAside from the [caveats](#caveats) of `Object` types when using custom yield handlers, any other type or value can be handled, even null, undefined, Symbols, anything. However, built-in yield handlers cannot be overridden.\n\nSee the above section on [Custom yieldable types](#custom-yieldable-types) for an example.\n\n-----\n##### `.coroutine(gfn : `[`GeneratorFunction`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/GeneratorFunction)`)` -\u003e `Function`\n**alias**: `.wrap(gfn : `[`GeneratorFunction`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/GeneratorFunction)`)` -\u003e `Function`\n\n**alias**: `.co.wrap(gfn : `[`GeneratorFunction`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/GeneratorFunction)`)` -\u003e `Function`\n\nThis calls [Bluebird.coroutine](http://bluebirdjs.com/docs/api/promise.coroutine.html) and returns the resulting function. When called, the returned function will return a Promise.\n\nThe `.wrap` alias is provided to be a drop-in replacement for `co.wrap`.\n\n-----\n##### `.execute(gfn : `[`GeneratorFunction`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/GeneratorFunction)`|`[`Generator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator)`, ...args : any[])` -\u003e `Promise\u003cany\u003e`\n**alias**: `.co(gfn : `[`GeneratorFunction`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/GeneratorFunction)`|`[`Generator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator)`, ...args : any[])` -\u003e `Promise\u003cany\u003e`\n\nThis calls [`.coroutine`](), then invokes the resulting function with the arguments provided, or just runs the generator object directly.\n\nIt is meant as a drop in replacement for tj/co `co`, like so:\n\n```javascript\n//import {co} from 'bluebird-co';\nvar co = require('bluebird-co').co;\n\nfunction* do_stuff(num) {\n    return num;\n}\n\nco(do_stuff, 10).then(function(result){\n    console.log(result); //10\n});\n```\n\n-----\n##### `.coroutine.yieldHanlders` -\u003e `Array\u003cFunction\u003e`\n\nExposes all custom yield handlers that have been added.\n\nbluebird-co expects this to be an array, so don't overwrite it with something silly.\n\n-----\n##### `.isThenable(value : any)` -\u003e `boolean`\n**alias**: `.isPromise(value : any)` -\u003e `boolean`\n\n```javascript\nfunction isThenable(value) {\n    return value \u0026\u0026 typeof value.then === 'function';\n}\n```\n\n-----\n##### `.isGenerator(value : any)` -\u003e `boolean`\n\nChecks if the value is a generator instance with `.next` and `.throw`.\n\n-----\n##### `.isGeneratorFunction(value : any)` -\u003e `boolean`\n\nChecks if the value is a [`GeneratorFunction`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/GeneratorFunction).\n\n-----\n# Changelog\n\n##### 2.2.0\n* Allow `.co` to accept generators and generator functions like `tj/co` does. (thanks [pkaminski](https://github.com/pkaminski))\n\n##### 2.1.2\n* Add `.co.wrap` alias for `.wrap`\n\n##### 2.1.1\n* Add simple quickstart section to README\n* Add usage docs with Babel 6\n\n##### 2.1.0\n* Added `.execute`/`.co` functions.\n* ~~(**BUILD**)~~(**FIXED**) As of this release, the build is failing only because Babel runtime is screwed up.\n\n##### 2.0.0\n* Improve docs\n* Upgrade to Bluebird 3.0\n* Upgrade to Babel 6 for build system\n* (**MAJOR**) Change behavior of classes that inherit from `Object`\n* Small internal improvements\n\n##### 1.3.1 - 1.3.2\n* Significantly improve performance of iterables.\n\n##### 1.3.0\n* Basic support for Iterables\n\n##### 1.2.0\n* Allow manual addition of the yield handler via requiring `bluebird-co/manual`\n* Exposed `toPromise` function in extra API\n\n##### 1.1.2 - 1.1.12\n* Optimizations and bugfixes\n\n##### 1.1.1\n* Don't export `isNativeObject`, because it isn't generic enough to use in most places, only internally under the right circumstances.\n\n##### 1.1.0\n* Differentiate between native objects and class instances. Fixes `addYieldHandler` functionality when used with class instances, but does not accept class instances as objects when there is not a handler for them.\n\n##### 1.0.0 - 1.0.5\n* Initial releases, documentation and bugfixes.\n\n-----\n## License\n\nThe MIT License (MIT)\n\nCopyright (c) 2015 Aaron Trent\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n[npm-image]: https://img.shields.io/npm/v/bluebird-co.svg?style=flat\n[npm-url]: https://npmjs.org/package/bluebird-co\n[downloads-image]: https://img.shields.io/npm/dm/bluebird-co.svg?style=flat\n[build-image]: https://travis-ci.org/novacrazy/bluebird-co.svg?branch=master\n[build-link]: https://travis-ci.org/novacrazy/bluebird-co\n[license-image]: https://img.shields.io/npm/l/bluebird-co.svg?style=flat\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnovacrazy%2Fbluebird-co","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnovacrazy%2Fbluebird-co","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnovacrazy%2Fbluebird-co/lists"}