Skip to content

Commit

Permalink
try to find callback in arguments
Browse files Browse the repository at this point in the history
  • Loading branch information
fengmk2 committed Nov 26, 2012
1 parent f9a4db0 commit a8e5f26
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 1 deletion.
13 changes: 12 additions & 1 deletion lib/mm.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,18 @@ exports.error = function (mod, method, error, timeout) {
}
timeout = timeout || 0;
muk(mod, method, function () {
var callback = arguments[arguments.length - 1];
var index = arguments.length - 1;
var callback = arguments[index];
while (typeof callback !== 'function') {
index--;
if (index < 0) {
break;
}
callback = arguments[index];
}
if (!callback) {
throw new TypeError('Can\'t find callback function');
}
setTimeout(function () {
callback(error);
}, timeout);
Expand Down
26 changes: 26 additions & 0 deletions test/foo.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
/*!
* mm - test/foo.js
* Copyright(c) 2012 fengmk2 <fengmk2@gmail.com>
* MIT Licensed
*/

"use strict";

/**
* Module dependencies.
*/

exports.get = function (query, callback, headers, cache) {
process.nextTick(callback.bind(null, null, {
query: query,
headers: headers,
cache: cache,
}));
};

exports.check = function (callback, a1, a2) {
process.nextTick(callback.bind(null, null, {
a1: a1,
a2: a2,
}));
};
36 changes: 36 additions & 0 deletions test/mm.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,42 @@ describe('mm.test.js', function () {
});
});

it('should work for callback is not the last params case', function (done) {
var foo = require('./foo');
done = pedding(3, done);

mm.error(foo, 'get', 'mock foo.get error');
foo.get('q1', function (err, data) {
should.exist(err);
err.message.should.equal('mock foo.get error');
should.not.exist(data);
done();
});

foo.get('q2', function (err, data) {
should.exist(err);
err.message.should.equal('mock foo.get error');
should.not.exist(data);
done();
}, { h1: 'h1' }, false);

mm.error(foo, 'check', 'mock foo.check error');
foo.check(function (err, data) {
should.exist(err);
err.message.should.equal('mock foo.check error');
should.not.exist(data);
done();
}, { h1: 'h1' }, false);
});

it('should throw error', function () {
var foo = require('./foo');
mm.error(foo, 'check', 'mock foo.check error');
(function () {
foo.check();
}).should.throw('Can\'t find callback function');
});

});

describe('http(s).request()', function () {
Expand Down

0 comments on commit a8e5f26

Please sign in to comment.