co

repository·master·Indexed 11 days ago

https://github.com/tj/co

A generator-based control flow library for Node.js and the browser that allows writing non-blocking, asynchronous code using generator syntax that resolves into Promises. Version 4.6.0 supports yieldables including Promises, thunks, arrays, objects, and generators.

Tokens
1.4K
Snippets
8
Records
10
Agent score
46%

What's inside co

  1. What are yieldables in co?

    master

    A yieldable is any object that co can process when it is yielded inside a generator. co supports the following yieldables:

    • Promises: Standard JavaScript promises.
    • Thunks: Functions that take a single argument (a callback). Note: Thunk support is for backwards compatibility and may be removed.
    • Arrays: Yielding an array resolves all yieldables within it in parallel.
    • Objects: Yielding an object resolves all yieldables within it in parallel.
    • Generators / Generator Functions: Used for delegation (though moving towards spec-compliant Promises is recommended).

    Nested yieldables are supported (e.g., an array containing objects containing promises).

  2. Platform Compatibility and Requirements

    master

    Promise Implementation

    co@4+ requires a Promise implementation. For Node.js < 0.11 or older browsers, you must include a Promise polyfill.

    Generator Support

    • Node.js v4+: Supported out of the box.
    • Node.js v0.11.x: You must use the --harmony-generators or --harmony flag.
    • Node.js < 0.11 or browsers without generator support: You must use gnode and/or regenerator.
  3. Handle errors in co generators

    master

    Errors in generators can be handled using standard try/catch blocks inside the generator. Any uncaught errors in the generator will be passed to the promise's rejection handler (the .catch() block of the co() call).

    var co = require('co');
    
    co(function* () {
      try {
        yield Promise.reject(new Error('boom'));
      } catch (err) {
        console.error(err.message); // "boom"
      }
    }).catch(onerror);
    
    function onerror(err) {
      console.error(err.stack);
    }
  4. Execute yieldables in parallel using Objects

    master

    When you yield an object, co resolves all values within the object in parallel and returns the results as an object with the same keys.

    var co = require('co');
    
    co(function* () {
      var res = yield {
        1: Promise.resolve(1),
        2: Promise.resolve(2),
      };
      console.log(res); // => { 1: 1, 2: 2 }
    }).catch(onerror);
  5. Execute yieldables in parallel using Arrays

    master

    When you yield an array, co resolves all elements in the array in parallel and returns the results as an array.

    var co = require('co');
    
    co(function* () {
      var res = yield [
        Promise.resolve(1),
        Promise.resolve(2),
        Promise.resolve(3),
      ];
      console.log(res); // => [1, 2, 3]
    }).catch(onerror);
  6. Convert a generator to a Promise-returning function with co.wrap()

    master

    Use co.wrap(fn*) to convert a generator function into a regular function that returns a Promise. This is useful when you want to use a generator as a standard asynchronous function.

    var fn = co.wrap(function* (val) {
      return yield Promise.resolve(val);
    });
    
    fn(true).then(function (val) {
      // handle result
    });
  7. Run a generator with co()

    master

    In co@4+, calling co() with a generator function returns a Promise. You can then use .then() to handle the resolved value or .catch() to handle errors. This allows you to write non-blocking code using generator syntax.

    var co = require('co');
    
    co(function* () {
      var result = yield Promise.resolve(true);
      return result;
    }).then(function (value) {
      console.log(value);
    }, function (err) {
      console.error(err.stack);
    });
  8. Execute a generator with co()

    master

    The co() function executes a generator function or a generator object and returns a Promise. It automatically handles the iteration of the generator and resolves the promise when the generator is done. You can pass arguments to the generator by providing them as subsequent arguments to co().

    Supported yieldable types include:

    • Promises
    • Thunks (functions following the (err, res) => ... pattern)
    • Generators and Generator Functions
    • Arrays of yieldables
    • Objects of yieldables
    const co = require('co');
    
    co(function* () {
      const result = yield somePromise();
      console.log(result);
    }).then(console.log).catch(console.error);
  9. Wrap a generator function with co.wrap()

    master

    Use co.wrap(fn) to convert a generator function into a standard function that returns a Promise. This is useful when you want to use a generator as a regular asynchronous function without manually calling co() every time it is invoked. The resulting function preserves the this context of the caller.

    const co = require('co');
    
    const wrapped = co.wrap(function* (name) {
      yield someAsyncOperation();
      return `Hello ${name}`;
    });
    
    // wrapped() now returns a Promise
    wrapped('World').then(console.log);