A set of high performance yield handlers for Bluebird coroutines

Overview

bluebird-co

NPM Version NPM Downloads MIT License Build Status

A set of high performance yield handlers for Bluebird coroutines.

Description

bluebird-co is a reimplementation of tj/co generator coroutines using bluebird, Bluebird.coroutine and Bluebird.coroutine.addYieldHandler to insert a yield handler that can transform all the same yieldable value types as tj/co and more.

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 (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

Usage

bluebird-co includes Bluebird as a peer dependency so that it will use any already installed instance of Bluebird, making it easier to bootstrap and integrate.

Using automatic bootstrapping:

require('bluebird-co');

and done.

Alternatively, manually adding the yield handler to Bluebird:

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 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

{
    "plugins": [
        ["transform-async-to-module-method", {
            "module": "bluebird-co",
            "method": "coroutine"
        }]
    ]
}

ES7 file to be transformed

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.

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

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

import {co} from 'bluebird-co';

co(...);
co.wrap(...);
For more examples, see the tj/co README and the Bluebird Coroutines API.

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 that works together in combination with the above yield handlers.

To do this, bluebird-co provides the .coroutine.addYieldHandler(fn) function, or just .addYieldHandler(fn) for short. The first is for strict compatibility with Bluebird.

Example of automatically fetching model data by yielding the model instance:

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:

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), 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, .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 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 for an example.


.coroutine(gfn : GeneratorFunction) -> Function

alias: .wrap(gfn : GeneratorFunction) -> Function

alias: .co.wrap(gfn : GeneratorFunction) -> Function

This calls Bluebird.coroutine and returns the resulting function. When called, the returned function will return a Promise.

The .wrap alias is provided to be a drop-in replacement for co.wrap.


.execute(gfn : GeneratorFunction|Generator, ...args : any[]) -> Promise<any>

alias: .co(gfn : GeneratorFunction|Generator, ...args : any[]) -> Promise<any>

This calls .coroutine, then invokes the resulting function with the arguments provided, or just runs the generator object directly.

It is meant as a drop in replacement for tj/co co, like so:

//import {co} from 'bluebird-co';
var co = require('bluebird-co').co;

function* do_stuff(num) {
    return num;
}

co(do_stuff, 10).then(function(result){
    console.log(result); //10
});

.coroutine.yieldHanlders -> Array<Function>

Exposes all custom yield handlers that have been added.

bluebird-co expects this to be an array, so don't overwrite it with something silly.


.isThenable(value : any) -> boolean

alias: .isPromise(value : any) -> boolean

function isThenable(value) {
    return value && typeof value.then === 'function';
}

.isGenerator(value : any) -> boolean

Checks if the value is a generator instance with .next and .throw.


.isGeneratorFunction(value : any) -> boolean

Checks if the value is a GeneratorFunction.


Changelog

2.2.0
  • Allow .co to accept generators and generator functions like tj/co does. (thanks pkaminski)
2.1.2
  • Add .co.wrap alias for .wrap
2.1.1
  • Add simple quickstart section to README
  • Add usage docs with Babel 6
2.1.0
  • Added .execute/.co functions.
  • (BUILD)(FIXED) As of this release, the build is failing only because Babel runtime is screwed up.
2.0.0
  • Improve docs
  • Upgrade to Bluebird 3.0
  • Upgrade to Babel 6 for build system
  • (MAJOR) Change behavior of classes that inherit from Object
  • Small internal improvements
1.3.1 - 1.3.2
  • Significantly improve performance of iterables.
1.3.0
  • Basic support for Iterables
1.2.0
  • Allow manual addition of the yield handler via requiring bluebird-co/manual
  • Exposed toPromise function in extra API
1.1.2 - 1.1.12
  • Optimizations and bugfixes
1.1.1
  • Don't export isNativeObject, because it isn't generic enough to use in most places, only internally under the right circumstances.
1.1.0
  • 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.
1.0.0 - 1.0.5
  • Initial releases, documentation and bugfixes.

License

The MIT License (MIT)

Copyright (c) 2015 Aaron Trent

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 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.

You might also like...

A Stacks DeFi app that automates covered call writing to generate sustainable, risk-adjusted yield.

A Stacks DeFi app that automates covered call writing to generate sustainable, risk-adjusted yield.

💰 Options Vault 💰 A Stacks DeFi app that automates covered call writing to generate sustainable, risk-adjusted yield. Options vaults allow you to al

Nov 16, 2022

🐦 Bluebird alternative within ~200 loc

NativeBird Ultralight promise extension compatible with Bluebird Introduction 中文介绍 As a pioneer in JavaScript async ecosystem, Bluebird is a great use

Jan 1, 2023

danfo.js is an open source, JavaScript library providing high performance, intuitive, and easy to use data structures for manipulating and processing structured data.

danfo.js is an open source, JavaScript library providing high performance, intuitive, and easy to use data structures for manipulating and processing structured data.

Danfojs: powerful javascript data analysis toolkit What is it? Danfo.js is a javascript package that provides fast, flexible, and expressive data stru

Dec 29, 2022

🏁 High performance subscription-based form state management for React

🏁 High performance subscription-based form state management for React

You build great forms, but do you know HOW users use your forms? Find out with Form Nerd! Professional analytics from the creator of React Final Form.

Jan 7, 2023

A cross platform high-performance graphics system.

A cross platform high-performance graphics system.

spritejs.org Spritejs is a cross platform high-performance graphics system, which can render graphics on web, node, desktop applications and mini-prog

Dec 24, 2022

Execute one command (or mount one Node.js middleware) and get an instant high-performance GraphQL API for your PostgreSQL database!

Execute one command (or mount one Node.js middleware) and get an instant high-performance GraphQL API for your PostgreSQL database!

PostGraphile Instant lightning-fast GraphQL API backed primarily by your PostgreSQL database. Highly customisable and extensible thanks to incredibly

Jan 4, 2023

Quasar Framework - Build high-performance VueJS user interfaces in record time

Quasar Framework - Build high-performance VueJS user interfaces in record time

Quasar Framework Build high-performance VueJS user interfaces in record time: responsive Single Page Apps, SSR Apps, PWAs, Browser extensions, Hybrid

Jan 9, 2023

A high-performance, dependency-free library for animated filtering, sorting, insertion, removal and more

MixItUp 3 MixItUp is a high-performance, dependency-free library for animated DOM manipulation, giving you the power to filter, sort, add and remove D

Dec 24, 2022

Ultra-high performance reactive programming

Ultra-high performance reactive programming

________________________________ ___ |/ /_ __ \_ ___/__ __/ __ /|_/ /_ / / /____ \__ / _ / / / / /_/ /____/ /_ / /_/ /_/ \____/__

Dec 28, 2022

Quasar Framework - Build high-performance VueJS user interfaces in record time

Quasar Framework - Build high-performance VueJS user interfaces in record time

Quasar Framework Build high-performance VueJS user interfaces in record time: responsive Single Page Apps, SSR Apps, PWAs, Browser extensions, Hybrid

Jan 3, 2023

A simple high-performance Redis message queue for Node.js.

RedisSMQ - Yet another simple Redis message queue A simple high-performance Redis message queue for Node.js. For more details about RedisSMQ design se

Dec 30, 2022

Mapbox Visual for Power BI - High performance, custom map visuals for Power BI dashboards

Mapbox Visual for Power BI - High performance, custom map visuals for Power BI dashboards

Mapbox Visual for Microsoft Power BI Make sense of your big & dynamic location data with the Mapbox Visual for Power BI. Quickly design high-performan

Nov 22, 2022

Lightweight, High Performance Particles in Canvas

Lightweight, High Performance Particles in Canvas

Sparticles https://sparticlesjs.dev Lightweight, High Performance Particles in Canvas. For those occasions when you 👏 just 👏 gotta 👏 have 👏 sparkl

Dec 29, 2022

A high performance MongoDB ORM for Node.js

Iridium A High Performance, IDE Friendly ODM for MongoDB Iridium is designed to offer a high performance, easy to use and above all, editor friendly O

Dec 14, 2022

High performance distributed data processing engine

High performance distributed data processing engine

High performance distributed data processing and machine learning. Skale provides a high-level API in Javascript and an optimized parallel execution e

Nov 16, 2022

A template project for building high-performance, portable, and safe serverless functions in Vercel.

A template project for building high-performance, portable, and safe serverless functions in Vercel.

Tutorial | Demo for image processing | Demo for tensorflow This is a Next.js project bootstrapped with create-next-app. This project is aimed to demon

Dec 8, 2022

Customizable, Pluginable, and High-Performance JavaScript-Based Scrollbar Solution.

Smooth Scrollbar Customizable, Flexible, and High Performance Scrollbars! Installation ⚠️ DO NOT use custom scrollbars unless you know what you are do

Jan 1, 2023

High performance JSX web views for S.js applications

High performance JSX web views for S.js applications

Surplus const name = S.data("world"), view = h1Hello {name()}!/h1; document.body.appendChild(view); Surplus is a compiler and runtime to all

Dec 30, 2022

AppRun is a JavaScript library for developing high-performance and reliable web applications using the elm inspired architecture, events and components.

AppRun is a JavaScript library for developing high-performance and reliable web applications using the elm inspired architecture, events and components.

AppRun AppRun is a JavaScript library for building reliable, high-performance web applications using the Elm-inspired architecture, events, and compon

Dec 20, 2022
Comments
  • Trying to use with koa

    Trying to use with koa

    I put the following in node_modules/koa/lib/application.js

    var co = require('co');
    
    const Promise = require('bluebird');
    Promise.longStackTraces();
    require('bluebird-co')
    co.wrap = function(fn) {
        return Promise.coroutine(fn);
    }
    

    is this the proper approach?

    good first bug 
    opened by gx0r 5
  • Support generators in co shim.

    Support generators in co shim.

    Fixes #4.

    Sorry about the huge diff on the build -- I guess either Babel changed its output formatting or the configuration isn't hermetic. Should I just remove the built file from the PR?


    This change is Reviewable

    opened by pkaminski 2
  • co shim doesn't accept generators like tj/co

    co shim doesn't accept generators like tj/co

    The tj/co drop-in replacement should also accept generators, not just generator functions, to be compatible with tj/co:

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

    opened by pkaminski 2
Owner
null
:bird: :zap: Bluebird is a full featured promise library with unmatched performance.

Got a question? Join us on stackoverflow, the mailing list or chat on IRC Introduction Bluebird is a fully featured promise library with focus on inno

Petka Antonov 20.2k Dec 31, 2022
🐦 Bluebird alternative within ~200 loc

NativeBird Ultralight promise extension compatible with Bluebird Introduction 中文介绍 As a pioneer in JavaScript async ecosystem, Bluebird is a great use

Yifeng Wang 60 Jan 1, 2023
:bird: :zap: Bluebird is a full featured promise library with unmatched performance.

Got a question? Join us on stackoverflow, the mailing list or chat on IRC Introduction Bluebird is a fully featured promise library with focus on inno

Petka Antonov 20.2k Jan 5, 2023
:bird: :zap: Bluebird is a full featured promise library with unmatched performance.

Got a question? Join us on stackoverflow, the mailing list or chat on IRC Introduction Bluebird is a fully featured promise library with focus on inno

Petka Antonov 20.2k Dec 31, 2022
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
🏆 ETHAmsterdam 2022 Finalist 👐 Support your favorite projects with yield

Yieldgate Yield Gate is a new monetisation tool for anyone to start receiving donations, or to support their favourite public goods projects, creators

null 16 Dec 15, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
Utilities to work with protocol handlers (like "vscode://") on the web.

Protocol Handlers Utilities to work with protocol handlers on the web. Why? While the Navigator API provides methods to .registerProtocolHandler() and

Artem Zakharchenko 11 Oct 1, 2022
End-to-End type safety for REST APIs written in Fastify. Only problem is you have to explicity export and register route handlers. LOL

Chino intelligence in japaneese End-to-End type safety for REST APIs written in Fastify. Only problem is you have to explicity export and register rou

sambit sahoo 2 Sep 12, 2022