@@ -19,14 +19,13 @@ module.exports = (arg) => {
1919 const subscriptions = { }
2020 ps . id = Math . random ( )
2121 return {
22- subscribe : ( topic , options , handler , callback ) => {
22+ subscribe : ( topic , handler , options , callback ) => {
2323 const defaultOptions = {
2424 discover : false
2525 }
2626
2727 if ( typeof options === 'function' ) {
28- callback = handler
29- handler = options
28+ callback = options
3029 options = defaultOptions
3130 }
3231
@@ -39,14 +38,15 @@ module.exports = (arg) => {
3938 if ( ! callback ) {
4039 return Promise . reject ( NotSupportedError ( ) )
4140 }
42- return callback ( NotSupportedError ( ) )
41+
42+ return process . nextTick ( ( ) => callback ( NotSupportedError ( ) ) )
4343 }
4444
4545 // promisify doesn't work as we always pass a
4646 // function as last argument (`handler`)
4747 if ( ! callback ) {
4848 return new Promise ( ( resolve , reject ) => {
49- subscribe ( topic , options , handler , ( err ) => {
49+ subscribe ( topic , handler , options , ( err ) => {
5050 if ( err ) {
5151 return reject ( err )
5252 }
@@ -55,24 +55,40 @@ module.exports = (arg) => {
5555 } )
5656 }
5757
58- subscribe ( topic , options , handler , callback )
58+ subscribe ( topic , handler , options , callback )
5959 } ,
60- unsubscribe : ( topic , handler ) => {
60+ unsubscribe : ( topic , handler , callback ) => {
6161 if ( ! isNode ) {
62- throw NotSupportedError ( )
62+ if ( ! callback ) {
63+ return Promise . reject ( NotSupportedError ( ) )
64+ }
65+
66+ return process . nextTick ( ( ) => callback ( NotSupportedError ( ) ) )
6367 }
6468
6569 if ( ps . listenerCount ( topic ) === 0 || ! subscriptions [ topic ] ) {
66- throw new Error ( `Not subscribed to '${ topic } '` )
70+ const err = new Error ( `Not subscribed to '${ topic } '` )
71+
72+ if ( ! callback ) {
73+ return Promise . reject ( err )
74+ }
75+
76+ return process . nextTick ( ( ) => callback ( err ) )
6777 }
6878
6979 ps . removeListener ( topic , handler )
7080
71- // Drop the request once we are actualy done
81+ // Drop the request once we are actually done
7282 if ( ps . listenerCount ( topic ) === 0 ) {
7383 subscriptions [ topic ] . abort ( )
7484 subscriptions [ topic ] = null
7585 }
86+
87+ if ( ! callback ) {
88+ return Promise . resolve ( )
89+ }
90+
91+ process . nextTick ( ( ) => callback ( ) )
7692 } ,
7793 publish : promisify ( ( topic , data , callback ) => {
7894 if ( ! isNode ) {
@@ -118,7 +134,7 @@ module.exports = (arg) => {
118134 }
119135 }
120136
121- function subscribe ( topic , options , handler , callback ) {
137+ function subscribe ( topic , handler , options , callback ) {
122138 ps . on ( topic , handler )
123139
124140 if ( subscriptions [ topic ] ) {
0 commit comments