@@ -3,7 +3,7 @@ import 'source-map-support/register';
33/**
44 * Emits events and hooks to synchronous and asynchronous listeners.
55 */
6- export class HookEmitter {
6+ class HookEmitter {
77 /**
88 * Constructs an HookEmitter object.
99 */
@@ -248,13 +248,13 @@ export class HookEmitter {
248248 let fired = null ;
249249 let pending = false ;
250250
251+ // construct the args
251252 const args = [ ...payload . args , function next ( err , result ) {
252- fired = { err, result } ;
253-
254- if ( err ) {
255- return Promise . reject ( err ) ;
256- }
253+ // we set the fired promise to this result/error
254+ fired = err ? Promise . reject ( err ) : Promise . resolve ( result ) ;
257255
256+ // if somebody mixes paradigms and calls next().then(),
257+ // at least their function will wait for the next listener
258258 return dispatch ( transform ( result , payload ) , i + 1 )
259259 . then ( result => {
260260 if ( pending ) {
@@ -266,11 +266,14 @@ export class HookEmitter {
266266 . catch ( reject ) ;
267267 } ] ;
268268
269+ // call the listener
269270 let result = listener . apply ( null , args ) ;
270271
272+ // if we got back a promise, we have to wait
271273 if ( result instanceof Promise ) {
272274 if ( fired ) {
273- return result . then ( resolve , reject ) ;
275+ return result
276+ . then ( resolve , reject ) ;
274277 }
275278
276279 return result
@@ -279,8 +282,12 @@ export class HookEmitter {
279282 . catch ( reject ) ;
280283 }
281284
285+ // result wasn't a promise, but maybe our old school next()
286+ // callback was called
282287 if ( fired ) {
283- return fired . err ? reject ( fired . err ) : resolve ( fired . result || payload ) ;
288+ return fired
289+ . then ( result => resolve ( result || payload ) )
290+ . catch ( reject ) ;
284291 }
285292
286293 // if the listener has more args than the number of args in
@@ -416,3 +423,6 @@ export class HookEmitter {
416423 return this ;
417424 }
418425}
426+
427+ export { HookEmitter } ;
428+ export default HookEmitter ;
0 commit comments