Skip to content

Commit

Permalink
Support first argument is function
Browse files Browse the repository at this point in the history
  • Loading branch information
yaniswang committed Nov 6, 2015
1 parent ff29d3c commit b449a49
Show file tree
Hide file tree
Showing 3 changed files with 77 additions and 2 deletions.
13 changes: 12 additions & 1 deletion lib/promiseclass.js
Expand Up @@ -31,7 +31,7 @@ const PromiseClass = {
let deferred = ChainPromise.defer();
let promise = deferred.promise;
let callback;
if(typeof args[args.length - 1] === 'function'){
if(isCallback(args[args.length - 1])){
// async mode
callback = args.pop();
}
Expand Down Expand Up @@ -93,4 +93,15 @@ const PromiseClass = {
}
};

// check callback
function isCallback(arg){
if(typeof arg === 'function'){
var str = String(arg);
if(/^function(\s+(done|callback|cb))\s*\(/.test(str) ||
/^function(\s+\w+)?\s*\(\s*(error|err|e)\s*(,|\))/i.test(str)){
return true;
}
}
return false;
}
module.exports = PromiseClass;
2 changes: 1 addition & 1 deletion package.json
@@ -1,6 +1,6 @@
{
"name": "promiseclass",
"version": "0.9.2",
"version": "0.9.3",
"description": "Create Promise chain Class",
"main": "./index",
"dependencies": {},
Expand Down
64 changes: 64 additions & 0 deletions test/case.spec.js
Expand Up @@ -76,3 +76,67 @@ describe('PromiseClass Generator test : ', function(){
});

});

describe('PromiseClass other test : ', function(){

it('all kind of callback should work well', function(done){
co(function*(){
var callbackCount = 0;
var App = PromiseClass.create({
method(n, done){
done(null, n);
}
});
var app = new App();
yield app.method(1, function(error){
!error && callbackCount ++;
});
yield app.method(2, function(err){
!err && callbackCount ++;
});
yield app.method(3, function(e){
!e && callbackCount ++;
});
yield app.method(4, function done(){
callbackCount ++;
});
yield app.method(5, function callback(){
callbackCount ++;
});
yield app.method(6, function cb(){
callbackCount ++;
});
expect(callbackCount).to.be(6);
done();
}).catch(done);
});

it('type of the first argument is function should work well', function(done){
co(function*(){
var App = PromiseClass.create({
method(n, done){
done();
}
});
var callbackCount = 0;
var app = new App();
yield app.method(function(){
throw new Error('test');
});
yield app.method(function(){
throw new Error('test');
}, function(err){
!err && callbackCount ++;
});
yield app.method(function(arg){
!arg;
throw new Error('test');
}, function done(){
callbackCount ++;
});
expect(callbackCount).to.be(2);
done();
}).catch(done);
});

});

0 comments on commit b449a49

Please sign in to comment.