Skip to content

Commit

Permalink
fix(options): pass options to try-catch-callback
Browse files Browse the repository at this point in the history
add tests and pass options to try-catch-callback
  • Loading branch information
tunnckoCore committed Oct 31, 2016
1 parent 3ba6afc commit aba375d
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 9 deletions.
24 changes: 15 additions & 9 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
29 changes: 29 additions & 0 deletions test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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' } })
})

0 comments on commit aba375d

Please sign in to comment.