Skip to content

Commit

Permalink
Support sync pre hooks
Browse files Browse the repository at this point in the history
  • Loading branch information
vkarpov15 committed Dec 12, 2014
1 parent 2ffc356 commit 1cc1b9f
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
27 changes: 26 additions & 1 deletion index.js
Expand Up @@ -50,7 +50,7 @@ Kareem.prototype.execPre = function(name, context, callback) {
return callback();
}
});
} else {
} else if (pre.fn.length > 0) {
pre.fn.call(context, function(error) {
if (error) {
if (done) {
Expand All @@ -71,12 +71,37 @@ Kareem.prototype.execPre = function(name, context, callback) {

next();
});
} else {
pre.fn.call(context);
if (++currentPre >= numPres) {
if (asyncPresLeft > 0) {
// Leave parallel hooks to run
return;
} else {
return process.nextTick(function() {
callback()
});
}
}
next();
}
};

next();
};

Kareem.prototype.execPost = function(name, context, callback) {
var posts = this._posts[name] || [];
var numPosts = posts.length;
var currentPost = 0;

if (!numPres) {
return process.nextTick(function() {
callback();
});
}
};

Kareem.prototype.pre = function(name, isAsync, fn, error) {
if ('boolean' !== typeof arguments[1]) {
error = fn;
Expand Down
19 changes: 19 additions & 0 deletions test/examples.test.js
Expand Up @@ -49,6 +49,25 @@ describe('pre hooks', function() {
});
});

it('can run fully synchronous pres', function(done) {
var count1 = 0;
var count2 = 0;

hooks.pre('cook', function() {
++count1;
});

hooks.pre('cook', function() {
++count2;
});

hooks.execPre('cook', null, function() {
assert.equal(1, count1);
assert.equal(1, count2);
done();
});
});

it('properly attaches context to pre hooks', function(done) {
hooks.pre('cook', function(done) {
this.bacon = 3;
Expand Down

0 comments on commit 1cc1b9f

Please sign in to comment.