From aba375d02e0057338b38fec96453f96a1318fa09 Mon Sep 17 00:00:00 2001 From: tunnckoCore Date: Tue, 1 Nov 2016 01:28:24 +0200 Subject: [PATCH] fix(options): pass options to try-catch-callback add tests and pass options to try-catch-callback --- index.js | 24 +++++++++++++++--------- test.js | 29 +++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 9 deletions(-) diff --git a/index.js b/index.js index 25fd31a..177dc79 100644 --- a/index.js +++ b/index.js @@ -67,25 +67,31 @@ var utils = require('./utils') * @api public */ -module.exports = function tryCatchCore (fn, cb) { +module.exports = function tryCatchCore (fn, cb, opts) { if (typeof fn !== 'function') { throw new TypeError('try-catch-core: expect `fn` to be a function') } if (typeof cb !== 'function') { return function thunk (done) { - tryCatch(fn, done) + tryCatch.call(this, fn, done, cb || opts) } } - tryCatch(fn, cb) + tryCatch.call(this, fn, cb, opts) } -function tryCatch (fn, cb) { +function tryCatch (fn, cb, opts) { if (typeof cb !== 'function') { throw new TypeError('try-catch-core: expect `cb` to be a function') } - if (utils.isAsync(fn)) { - fn(utils.once(utils.dezalgo(cb))) - return - } - utils.tryCatchCallback(fn, utils.once(cb), true) + cb = utils.isAsync(fn) + ? utils.once(utils.dezalgo(cb)) + : utils.once(cb) + opts = opts && typeof opts === 'object' + ? opts + : {} + opts.passCallback = typeof opts.passCallback === 'boolean' + ? opts.passCallback + : true + + utils.tryCatchCallback.call(this, fn, cb, opts) } diff --git a/test.js b/test.js index 37139a5..405d5b0 100644 --- a/test.js +++ b/test.js @@ -93,3 +93,32 @@ test('should pass result from `fs.readFile` to the callback', function (done) { done() }) }) + +test('should be able to pass custom arguments through options', function (done) { + tryCatchCore(function (foo, bar, next) { + test.strictEqual(arguments.length, 3) + test.strictEqual(foo, 1) + test.strictEqual(bar, 2) + next(null, foo) + }, function (err, res) { + test.strictEqual(err, null) + test.strictEqual(res, 1) + done() + }, { args: [ 1, 2 ] }) +}) + +test('should not pass a callback to `fn` if passCallback:false', function (done) { + tryCatchCore(function () { + test.strictEqual(arguments.length, 0) + }, function (err, res) { + test.strictEqual(err, null) + test.strictEqual(res, undefined) + done() + }, { passCallback: false }) +}) + +test('should pass custom context to `fn` through options', function (done) { + tryCatchCore(function () { + test.strictEqual(this.foo, 'bar') + }, done, { context: { foo: 'bar' } }) +})