Skip to content

Commit 1a8d3ba

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

File tree

1 file changed

+17
-23
lines changed

1 file changed

+17
-23
lines changed

index.js

Lines changed: 17 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,10 @@
33
const path = require('path');
44
const net = require('net');
55
const _ = require('lodash');
6+
const { EventEmitter } = require('events');
67

7-
class LightningClient {
8+
9+
class LightningClient extends EventEmitter {
810
constructor(rpcPath) {
911
if (!path.isAbsolute(rpcPath)) {
1012
throw new Error('The rpcPath must be an absolute path');
@@ -14,6 +16,7 @@ class LightningClient {
1416

1517
console.log(`Connecting to ${rpcPath}`);
1618

19+
super();
1720
this.rpcPath = rpcPath;
1821
this.reconnectWait = 0.5;
1922
this.reconnectTimeout = null;
@@ -41,8 +44,6 @@ class LightningClient {
4144
});
4245
});
4346

44-
this.waitingFor = {};
45-
4647
this.client.on('data', data => {
4748
_.each(LightningClient.splitJSON(data.toString()), str => {
4849
let dataObject = {};
@@ -52,12 +53,7 @@ class LightningClient {
5253
return;
5354
}
5455

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];
56+
_self.emit('res:'+dataObject.id, dataObject)
6157
});
6258
});
6359
}
@@ -131,22 +127,20 @@ class LightningClient {
131127

132128
// Wait for the client to connect
133129
return this.clientConnectionPromise
134-
.then(() => {
130+
.then(() => new Promise((resolve, reject) => {
135131
// 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));
132+
this.once('res:'+callInt, response => {
133+
if (_.isNil(response.error)) {
134+
resolve(response.result);
135+
return;
136+
}
137+
138+
reject(new Error(response.error));
148139
});
149-
});
140+
141+
// Send the command
142+
_self.client.write(JSON.stringify(sendObj));
143+
}));
150144
}
151145

152146
devBlockheight() {

0 commit comments

Comments
 (0)