bluebird-co
=============
[![NPM Version][npm-image]][npm-url]
[![NPM Downloads][downloads-image]][npm-url]
[![MIT License][license-image]][npm-url]
[![Build Status][build-image]][build-link]
A set of high performance yield handlers for Bluebird coroutines.
# Description
bluebird-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.
[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.
Combined 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.
# Quickstart
To install:
`npm install bluebird-co`
Ensure Bluebird is installed:
`npm install bluebird@3`
# Performance
Squeezing 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.
[See here for detailed benchmarks](https://github.com/novacrazy/bluebird-co/tree/master/benchmark)
# Usage
bluebird-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.
Using automatic bootstrapping:
```javascript
require('bluebird-co');
```
and done.
Alternatively, manually adding the yield handler to Bluebird:
```javascript
var Promise = require('bluebird'),
bluebird_co = require('bluebird-co/manual');
Promise.coroutine.addYieldHandler(bluebird_co.toPromise);
var fn = Promise.coroutine(function*(){
//do stuff
});
fn().then(...);
```
In 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.
### Usage with Babel 6:
Babel 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.
**.babelrc file**
```javascript
{
"plugins": [
["transform-async-to-module-method", {
"module": "bluebird-co",
"method": "coroutine"
}]
]
}
```
**ES7 file to be transformed**
```javascript
async function fn() {
//do stuff
}
fn().then(...);
```
# Example coroutines
**Note**: bluebird-co has to be added to Bluebird via automatic bootstrapping or manual addition before these snippets can work.
```javascript
var Promise = require('bluebird');
var fs = Promise.promisifyAll(require('fs'));
var myAsyncFunction = Promise.coroutine(function*() {
var results = yield [Promise.delay( 10 ).return( 42 ),
readFileAsync( 'index.js', 'utf-8' ),
[1, Promise.resolve( 12 )]];
console.log(results); //[42, "somefile contents", [1, 12]]
});
myAsyncFunction().then(...);
```
### ES7 version
```javascript
import Promise from 'bluebird';
import {readFile} from 'fs';
let readFileAsync = Promise.promisify(readFile);
async function myAsyncFunction() {
let results = await [Promise.delay( 10 ).return( 42 ),
readFileAsync( 'index.js', 'utf-8' ),
[1, Promise.resolve( 12 )]];
console.log(results); //[42, "somefile contents", [1, 12]]
}
myAsyncFunction().then(...);
```
### tj/co drop-in replacement
```javascript
import {co} from 'bluebird-co';
co(...);
co.wrap(...);
```
##### 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).
# Yieldable Types
* Promises
* Arrays
* Objects
* Generators and GeneratorFunctions
* Iterables (like `new Set([1, 2, 3]).values()`)
* Functions (as Thunks)
* Custom data types via [`.addYieldHandler(fn)`#addyieldhandlerfn--function
* Any combination or nesting of the above.
# Custom yieldable types
It 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.
To 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.
Example of automatically fetching model data by yielding the model instance:
```javascript
import {coroutine} from 'bluebird-co';
class MyModel {
async fetch() {
//do stuff
return data;
}
}
coroutine.addYieldHandler(function(value) {
if(value instanceof MyModel) {
return value.fetch();
}
});
async function test() {
let model = new MyModel();
let data = await model; //calls model.fetch() and waits on it.
}
```
Additionally, you can even access the array of yield handlers manually if you ever need to remove one, like so:
```javascript
console.log(coroutine.yieldHandlers); //array of functions
```
#### Caveats:
Although 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.
# API
All functions and properties listed below are exported by the `bluebird-co` module.
-----
##### `.toPromise(value : any)` -> `Promise<any> | any`
`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.
In 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.
-----
##### `.addYieldHandler(fn : Function)`
**alias**: `.coroutine.addYieldHandler(fn : Function)`
Very 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.
Aside 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.
See the above section on [Custom yieldable types](#custom-yieldable-types) for an example.
-----
##### `.coroutine(gfn : `[`GeneratorFunction`](https://developer.mozilla.org/en-US/d
没有合适的资源?快使用搜索试试~ 我知道了~
auto.js安装包:app-v6-armeabi-v7a-release-unsigned-signed.apk
共2000个文件
js:1258个
xml:684个
txt:24个
0 下载量 61 浏览量
2024-02-11
18:32:40
上传
评论
收藏 68.46MB RAR 举报
温馨提示
auto.js安装包:app-v6-armeabi-v7a-release-unsigned-signed.apk
资源推荐
资源详情
资源评论
收起资源包目录
auto.js安装包:app-v6-armeabi-v7a-release-unsigned-signed.apk (2000个子文件)
game.html 432KB
网页.html 956B
cheerio.js 609KB
lodash.js 531KB
vconsole.min.js 208KB
bluebird.js 180KB
stream-browserify.js 116KB
core.js 113KB
beautify.js 112KB
buffer.js 80KB
贪吃蛇重力感应版.js 78KB
lodash.min.js 71KB
util.js 62KB
axios.min.js 38KB
表格控件-内置图标查看器.js 29KB
event-stream.js 22KB
__images__.js 21KB
__json2__.js 18KB
events.js 17KB
_baseConvert.js 16KB
__util__.js 15KB
string_decoder.js 13KB
__ui__.js 13KB
core.min.js 12KB
template.js 10KB
_mapping.js 10KB
yield_handler.js 10KB
__dialogs__.js 10KB
XMLHttpRequest.js 9KB
__app__.js 9KB
__automator__.js 8KB
jvm-npm.js 8KB
wrapperLodash.js 7KB
__http__.js 7KB
AutoX注入webview.js 6KB
debounce.js 6KB
index.js 6KB
E4X.js 6KB
__$crypto__.js 6KB
_baseClone.js 5KB
__$zip__.js 5KB
贪吃蛇.js 5KB
thunks.js 5KB
object-observe-lite.min.js 5KB
generators.js 5KB
__globals__.js 4KB
OCR截图识别.js 4KB
arrays.js 4KB
objects.js 4KB
stream.js 4KB
OCR截图识别.js 4KB
Gruntfile.js 4KB
_equalByTag.js 4KB
errors.js 4KB
_createWrap.js 4KB
显示常用传感器信息.js 4KB
图片处理.js 4KB
__console__.js 4KB
待办事项.js 4KB
FormData.js 3KB
_deburrLetter.js 3KB
免root屏幕录制.js 3KB
truncate.js 3KB
_createHybrid.js 3KB
_mergeData.js 3KB
init.js 3KB
_baseMergeDeep.js 3KB
_unicodeWords.js 3KB
_baseIsEqualDeep.js 3KB
_equalObjects.js 3KB
WannaCry(仅为娱乐).js 3KB
用户调查.js 3KB
throttle.js 3KB
_equalArrays.js 3KB
iterables.js 3KB
界面模板一.js 2KB
array.js 2KB
result_adapter.js 2KB
random.js 2KB
函数图像高级版.js 2KB
transform.js 2KB
_baseIntersection.js 2KB
_initCloneByTag.js 2KB
_baseSortedIndexBy.js 2KB
ThreadPool.js 2KB
_createFlow.js 2KB
mixin.js 2KB
__unit_test__.js 2KB
memoize.js 2KB
_baseIsTypedArray.js 2KB
文本控件.js 2KB
lang.js 2KB
_createRecurry.js 2KB
bindKey.js 2KB
打印常用传感器信息.js 2KB
isEmpty.js 2KB
__floaty__.js 2KB
_baseDifference.js 2KB
_baseUniq.js 2KB
__continuation__.js 2KB
共 2000 条
- 1
- 2
- 3
- 4
- 5
- 6
- 20
资源评论
Dontla
- 粉丝: 1w+
- 资源: 26
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功