diff --git a/lib/hub.js b/lib/hub.js index 84be893..3ba4bf5 100644 --- a/lib/hub.js +++ b/lib/hub.js @@ -331,34 +331,36 @@ function create() { return cachedEntries(matchersCache, type, event, re, eachMatcher); } - function doneOnListeners(scope, re, args, e, values, callback) { - var result = values ? (scope.allResults ? - values : values[values.length - 1]) : null; - if (scope.stopped) { - done(scope, callback, e, result); - } else { - args = [e, result]; - var fns = findListeners('after', scope.event, re); - emit(fns, scope, args, [], function (err, values) { + function createEmitAfter(finder, then) { + return function (scope, re, args, callback) { + var fns = finder('after', scope.event, re); + emit(fns, scope, args, [], function (err) { if (scope.stopped) { done(scope, callback, err); } else { if (err) { args[0] = combinedErrors(args[0], err); } - var fns = findMatchers('after', scope.event, re); - emit(fns, scope, args, [], function (err) { - if (scope.stopped) { - done(scope, callback, err); - } else { - if (err) { - args[0] = combinedErrors(args[0], err); - } - done(scope, callback, args[0], args[1]); - } - }); + then(scope, re, args, callback); } }); + }; + } + + function doneAfterMatchers(scope, re, args, callback) { + done(scope, callback, args[0], args[1]); + } + + var doneAfterListeners = createEmitAfter(findMatchers, doneAfterMatchers); + var emitAfterListeners = createEmitAfter(findListeners, doneAfterListeners); + + function doneOnListeners(scope, re, args, e, values, callback) { + var result = values ? (scope.allResults ? + values : values[values.length - 1]) : null; + if (scope.stopped) { + done(scope, callback, e, result); + } else { + emitAfterListeners(scope, re, [e, result], callback); } }