Skip to content

Commit

Permalink
support regular functions that throw
Browse files Browse the repository at this point in the history
  • Loading branch information
jonathanong committed Mar 18, 2015
1 parent 1d3cb91 commit 9d996f2
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 7 deletions.
3 changes: 2 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,12 @@ co.wrap = function (fn) {

function co(gen) {
var ctx = this;
if (typeof gen === 'function') gen = gen.call(this);

// 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.call(ctx);
if (!gen || typeof gen.next !== 'function') return resolve(gen);

onFulfilled();
Expand Down
20 changes: 14 additions & 6 deletions test/promises.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,21 +69,29 @@ describe('co(function) -> promise', function(){
})
})

it('return resolve promise', function(done){
co(function(){
it('return resolve promise', function(){
return co(function(){
return Promise.resolve(1);
}).then(function(data){
assert.equal(data, 1);
done();
})
})

it('return reject promise', function(done){
co(function(){
it('return reject promise', function(){
return co(function(){
return Promise.reject(1);
}).catch(function(data){
assert.equal(data, 1);
done();
})
})

it('should catch errors', function(){
return co(function(){
throw new Error('boom');
}).then(function () {
throw new Error('nope');
}).catch(function (err) {
assert.equal(err.message, 'boom');
});
})
})

0 comments on commit 9d996f2

Please sign in to comment.