From b449a499bf41edf35369b13013984005ea3c1622 Mon Sep 17 00:00:00 2001 From: Yanis Wang Date: Fri, 6 Nov 2015 23:58:05 +0800 Subject: [PATCH] Support first argument is function --- lib/promiseclass.js | 13 ++++++++- package.json | 2 +- test/case.spec.js | 64 +++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 77 insertions(+), 2 deletions(-) diff --git a/lib/promiseclass.js b/lib/promiseclass.js index 0af415d..a913d8f 100644 --- a/lib/promiseclass.js +++ b/lib/promiseclass.js @@ -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(); } @@ -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; diff --git a/package.json b/package.json index 3ac9bc3..dffa735 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "promiseclass", - "version": "0.9.2", + "version": "0.9.3", "description": "Create Promise chain Class", "main": "./index", "dependencies": {}, diff --git a/test/case.spec.js b/test/case.spec.js index 71021f8..36b1b1e 100644 --- a/test/case.spec.js +++ b/test/case.spec.js @@ -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); + }); + +});