Skip to content

Commit 38a7eed

Browse files
committed
Simplify request/response association using EventEmitter's once()
1 parent b0a1b02 commit 38a7eed

1 file changed

Lines changed: 16 additions & 23 deletions

File tree

index.js

Lines changed: 16 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,10 @@
22

33
const path = require('path');
44
const net = require('net');
5+
const {EventEmitter} = require('events');
56
const _ = 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

Comments
 (0)