Skip to content

Commit

Permalink
feat: add option to check wrapped function return value for promises
Browse files Browse the repository at this point in the history
  • Loading branch information
vkarpov15 committed May 16, 2018
1 parent 0fc21f9 commit c9d7dd1
Showing 1 changed file with 19 additions and 1 deletion.
20 changes: 19 additions & 1 deletion index.js
Expand Up @@ -260,6 +260,7 @@ Kareem.prototype.wrap = function(name, fn, context, args, options) {
const _this = this;

options = options || {};
const checkForPromise = options.checkForPromise;

this.execPre(name, context, args, function(error) {
if (error) {
Expand All @@ -273,7 +274,24 @@ Kareem.prototype.wrap = function(name, fn, context, args, options) {
}

const end = (typeof lastArg === 'function' ? args.length - 1 : args.length);
fn.apply(context, args.slice(0, end).concat(_cb));
const numParameters = fn.length;
const ret = fn.apply(context, args.slice(0, end).concat(_cb));

if (checkForPromise) {
if (ret != null && typeof ret.then === 'function') {
// Thenable, use it
return ret.then(
res => _cb(null, res),
err => _cb(err)
);
}

// If `fn()` doesn't have a callback argument and doesn't return a
// promise, assume it is sync
if (numParameters < end + 1) {
return _cb(null, ret);
}
}

function _cb() {
const args = arguments;
Expand Down

0 comments on commit c9d7dd1

Please sign in to comment.