Skip to content

Commit

Permalink
handle this.callback called synchronously
Browse files Browse the repository at this point in the history
  • Loading branch information
cloudhead committed Jun 8, 2010
1 parent 311df5f commit 062450c
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
13 changes: 11 additions & 2 deletions lib/vows/context.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,19 @@ this.Context = function (vow, ctx, env) {
this.env.context = this;
this.env.__defineGetter__('callback', function () {
that._callback = true;

return function (e, res) {
var args = Array.prototype.slice.call(arguments, 1);
if (e) { that.emitter.emit('error', e) }
else { that.emitter.emit.apply(that.emitter, ['success'].concat(args)) }
var emit = function () {
if (e) { that.emitter.emit('error', e) }
else { that.emitter.emit.apply(that.emitter, ['success'].concat(args)) }
};
// If `this.callback` is called synchronously,
// the emitter will not have been set yet,
// so we defer the emition, that way it'll behave
// asynchronously.
if (that.emitter) { emit() }
else { process.nextTick(emit) }
};
});
this.name = (ctx.name ? ctx.name + ' ' : '') +
Expand Down
8 changes: 8 additions & 0 deletions test/vows-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,14 @@ vows.describe("Vows").addVows({
assert.equal(e, "ERROR");
assert.equal(res, undefined);
}
},
"using this.callback synchronously": {
topic: function () {
this.callback(null, 'hello');
},
"should work the same as returning a value": function (res) {
assert.equal(res, 'hello');
}
}
}
}).addVows({
Expand Down

0 comments on commit 062450c

Please sign in to comment.