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

Bluebird version #324

Open
wants to merge 3 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
246 changes: 246 additions & 0 deletions co-bluebird.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,246 @@

/**
* Swap default Promise
* look http://bluebirdjs.com/docs/why-bluebird.html
*/

var Promise = require('bluebird')

/**
* slice() reference.
*/

var slice = Array.prototype.slice;

/**
* Expose `co`.
*/

module.exports = co['default'] = co.co = co;

/**
* Wrap the given generator `fn` into a
* function that returns a promise.
* This is a separate function so that
* every `co()` call doesn't create a new,
* unnecessary closure.
*
* @param {GeneratorFunction} fn
* @return {Function}
* @api public
*/

co.wrap = function (fn) {
createPromise.__generatorFunction__ = fn;
return createPromise;
function createPromise() {
return co.call(this, fn.apply(this, arguments));
}
};

/**
* Execute the generator function or a generator
* and return a promise.
*
* @param {Function} fn
* @return {Promise}
* @api public
*/

function co(gen) {
var ctx = this;
var args = slice.call(arguments, 1);

// we wrap everything in a promise to avoid promise chaining,
// which leads to memory leak errors.
// see https://github.com/tj/co/issues/180
return new Promise(function(resolve, reject) {
if (typeof gen === 'function') gen = gen.apply(ctx, args);
if (!gen || typeof gen.next !== 'function') return resolve(gen);

onFulfilled();

/**
* @param {Mixed} res
* @return {Promise}
* @api private
*/

function onFulfilled(res) {
var ret;
try {
ret = gen.next(res);
} catch (e) {
return reject(e);
}
next(ret);
return null;
}

/**
* @param {Error} err
* @return {Promise}
* @api private
*/

function onRejected(err) {
var ret;
try {
ret = gen.throw(err);
} catch (e) {
return reject(e);
}
next(ret);
}

/**
* Get the next value in the generator,
* return a promise.
*
* @param {Object} ret
* @return {Promise}
* @api private
*/

function next(ret) {
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, '
+ 'but the following object was passed: "' + String(ret.value) + '"'));
}
});
}

/**
* Convert a `yield`ed value into a promise.
*
* @param {Mixed} obj
* @return {Promise}
* @api private
*/

function toPromise(obj) {
if (!obj) return 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);
if (Array.isArray(obj)) return arrayToPromise.call(this, obj);
if (isObject(obj)) return objectToPromise.call(this, obj);
return obj;
}

/**
* Convert a thunk to a promise.
*
* @param {Function}
* @return {Promise}
* @api private
*/

function thunkToPromise(fn) {
var ctx = this;
return new Promise(function (resolve, reject) {
fn.call(ctx, function (err, res) {
if (err) return reject(err);
if (arguments.length > 2) res = slice.call(arguments, 1);
resolve(res);
});
});
}

/**
* Convert an array of "yieldables" to a promise.
* Uses `Promise.all()` internally.
*
* @param {Array} obj
* @return {Promise}
* @api private
*/

function arrayToPromise(obj) {
return Promise.all(obj.map(toPromise, this));
}

/**
* Convert an object of "yieldables" to a promise.
* Uses `Promise.all()` internally.
*
* @param {Object} obj
* @return {Promise}
* @api private
*/

function objectToPromise(obj){
var results = new obj.constructor();
var keys = Object.keys(obj);
var promises = [];
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var promise = toPromise.call(this, obj[key]);
if (promise && isPromise(promise)) defer(promise, key);
else results[key] = obj[key];
}
return Promise.all(promises).then(function () {
return results;
});

function defer(promise, key) {
// predefine the key in the result
results[key] = undefined;
promises.push(promise.then(function (res) {
results[key] = res;
}));
}
}

/**
* Check if `obj` is a promise.
*
* @param {Object} obj
* @return {Boolean}
* @api private
*/

function isPromise(obj) {
return 'function' == typeof obj.then;
}

/**
* Check if `obj` is a generator.
*
* @param {Mixed} obj
* @return {Boolean}
* @api private
*/

function isGenerator(obj) {
return 'function' == typeof obj.next && 'function' == typeof obj.throw;
}

/**
* Check if `obj` is a generator function.
*
* @param {Mixed} obj
* @return {Boolean}
* @api private
*/

function isGeneratorFunction(obj) {
var constructor = obj.constructor;
if (!constructor) return false;
if ('GeneratorFunction' === constructor.name || 'GeneratorFunction' === constructor.displayName) return true;
return isGenerator(constructor.prototype);
}

/**
* Check for plain object.
*
* @param {Mixed} val
* @return {Boolean}
* @api private
*/

function isObject(val) {
return Object == val.constructor;
}
6 changes: 5 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,14 @@
"mz": "^1.0.2"
},
"scripts": {
"test": "mocha --harmony",
"test": "mocha --recursive --harmony",
"test-cov": "node --harmony node_modules/.bin/istanbul cover ./node_modules/.bin/_mocha -- --reporter dot",
"test-travis": "node --harmony node_modules/.bin/istanbul cover ./node_modules/.bin/_mocha --report lcovonly -- --reporter dot",
"prepublish": "npm run browserify",
"browserify": "browserify index.js -o ./co-browser.js -s co"
},
"files": [
"co-bluebird.js",
"co-browser.js",
"index.js"
],
Expand All @@ -31,5 +32,8 @@
"engines": {
"iojs": ">= 1.0.0",
"node": ">= 0.12.0"
},
"dependencies": {
"bluebird": "^3.5.1"
}
}
16 changes: 16 additions & 0 deletions test/bluebird/arguments.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@

var assert = require('assert');

var co = require('../../co-bluebird');

describe('co(gen, args)', function () {
it('should pass the rest of the arguments', function () {
return co(function *(num, str, arr, obj, fun){
assert(num === 42);
assert(str === 'forty-two');
assert(arr[0] === 42);
assert(obj.value === 42);
assert(fun instanceof Function)
}, 42, 'forty-two', [42], { value: 42 }, function () {});
})
})
35 changes: 35 additions & 0 deletions test/bluebird/arrays.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@

var read = require('mz/fs').readFile;
var assert = require('assert');

var co = require('../../co-bluebird');

describe('co(* -> yield [])', function(){
it('should aggregate several promises', function(){
return co(function *(){
var a = read('index.js', 'utf8');
var b = read('LICENSE', 'utf8');
var c = read('package.json', 'utf8');

var res = yield [a, b, c];
assert.equal(3, res.length);
assert(~res[0].indexOf('exports'));
assert(~res[1].indexOf('MIT'));
assert(~res[2].indexOf('devDependencies'));
});
})

it('should noop with no args', function(){
return co(function *(){
var res = yield [];
assert.equal(0, res.length);
});
})

it('should support an array of generators', function(){
return co(function*(){
var val = yield [function*(){ return 1 }()]
assert.deepEqual(val, [1])
})
})
})
16 changes: 16 additions & 0 deletions test/bluebird/context.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@

var assert = require('assert');

var co = require('../../co-bluebird');

var ctx = {
some: 'thing'
};

describe('co.call(this)', function () {
it('should pass the context', function () {
return co.call(ctx, function *(){
assert(ctx == this);
});
})
})
46 changes: 46 additions & 0 deletions test/bluebird/generator-functions.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@

var assert = require('assert');
var co = require('../../co-bluebird');

function sleep(ms) {
return function(done){
setTimeout(done, ms);
}
}

function *work() {
yield sleep(50);
return 'yay';
}

describe('co(fn*)', function(){
describe('with a generator function', function(){
it('should wrap with co()', function(){
return co(function *(){
var a = yield work;
var b = yield work;
var c = yield work;

assert('yay' == a);
assert('yay' == b);
assert('yay' == c);

var res = yield [work, work, work];
assert.deepEqual(['yay', 'yay', 'yay'], res);
});
})

it('should catch errors', function(){
return co(function *(){
yield function *(){
throw new Error('boom');
};
}).then(function () {
throw new Error('wtf')
}, function (err) {
assert(err);
assert(err.message == 'boom');
});
})
})
})