22
33const path = require ( 'path' ) ;
44const net = require ( 'net' ) ;
5+ const { EventEmitter} = require ( 'events' ) ;
56const _ = require ( 'lodash' ) ;
67
7- class LightningClient {
8+ class LightningClient extends EventEmitter {
89 constructor ( rpcPath ) {
910 if ( ! path . isAbsolute ( rpcPath ) ) {
1011 throw new Error ( 'The rpcPath must be an absolute path' ) ;
@@ -14,6 +15,7 @@ class LightningClient {
1415
1516 console . log ( `Connecting to ${ rpcPath } ` ) ;
1617
18+ super ( ) ;
1719 this . rpcPath = rpcPath ;
1820 this . reconnectWait = 0.5 ;
1921 this . reconnectTimeout = null ;
@@ -41,8 +43,6 @@ class LightningClient {
4143 } ) ;
4244 } ) ;
4345
44- this . waitingFor = { } ;
45-
4646 this . client . on ( 'data' , data => {
4747 _ . each ( LightningClient . splitJSON ( data . toString ( ) ) , str => {
4848 let dataObject = { } ;
@@ -52,12 +52,7 @@ class LightningClient {
5252 return ;
5353 }
5454
55- if ( ! _ . isFunction ( _self . waitingFor [ dataObject . id ] ) ) {
56- return ;
57- }
58-
59- _self . waitingFor [ dataObject . id ] . call ( _self , dataObject ) ;
60- delete _self . waitingFor [ dataObject . id ] ;
55+ _self . emit ( 'res:' + dataObject . id , dataObject ) ;
6156 } ) ;
6257 } ) ;
6358 }
@@ -131,22 +126,20 @@ class LightningClient {
131126
132127 // Wait for the client to connect
133128 return this . clientConnectionPromise
134- . then ( ( ) => {
129+ . then ( ( ) => new Promise ( ( resolve , reject ) => {
135130 // Wait for a response
136- return new Promise ( ( resolve , reject ) => {
137- this . waitingFor [ callInt ] = response => {
138- if ( _ . isNil ( response . error ) ) {
139- resolve ( response . result ) ;
140- return ;
141- }
142-
143- reject ( new Error ( response . error ) ) ;
144- } ;
145-
146- // Send the command
147- _self . client . write ( JSON . stringify ( sendObj ) ) ;
131+ this . once ( 'res:' + callInt , response => {
132+ if ( _ . isNil ( response . error ) ) {
133+ resolve ( response . result ) ;
134+ return ;
135+ }
136+
137+ reject ( new Error ( response . error ) ) ;
148138 } ) ;
149- } ) ;
139+
140+ // Send the command
141+ _self . client . write ( JSON . stringify ( sendObj ) ) ;
142+ } ) ) ;
150143 }
151144
152145 devBlockheight ( ) {
0 commit comments