Answer the question
In order to leave comments, you need to log in
How to get 2 responses from the server using Promise?
On request from the server, 2 response lines are returned in turn, In the code I get only one!
const net = require("net");
const HOST = '192.168.0.75';
const PORT = '30001';
class Api {
constructor(host, port) {
this.HOST = host || HOST;
this.PORT = port || PORT;
this.socket = new net.Socket();
this.init();
}
init() {
const client = this;
client.socket.connect(client.PORT, client.HOST, () => {
console.log(`Client connected to: ${client.HOST}:${client.PORT}`);
});
client.socket.on('close', () => {
console.log('FiscalAPI: connection closed');
});
};
sendCommand(cmd) {
const client = this;
return new Promise((resolve, reject) => {
if(cmd) {
client.socket.write(cmd + '\u0000\r\n');
}
client.socket.on('data', (data) => {
resolve(data.toString());
});
client.socket.on('error', (error) => {
reject(error);
});
});
};
checkPumpState(dispenser_index){
this.sendCommand('0;open')
.then((data) => {
console.log(data);
return this.sendCommand(`0;dispenser_get;${dispenser_index};1`);
})
.then((data) => {
console.log(data);
return this.sendCommand(`0;store_get;0;16\u0000\r\n`);
})
.then((data) => {
console.log(data);
})
.catch((error) => console.log(error));
}
}
Answer the question
In order to leave comments, you need to log in
I don’t really understand what’s going on here, but I’ll assume that your event client.socket.on('data')
is called twice - for each response from the server. And you return the promise as soon as you get the first answer.
UPD accept all data but only return on 'end' event
sendCommand(cmd) {
if(cmd) {
this.socket.write(cmd + '\u0000\r\n');
}
return new Promise((resolve, reject) => {
const chunks = [];
const handleData = chunk => {
chunks.push(chunk);
};
const handleError = err => {
reject(err);
};
const handleEnd => {
const data = Buffer.concat(chunks).toString().match(/.*?\r\n/g);
resolve(data);
}
this.socket.on('data', handleData);
this.socket.on('error', handleError);
this.socket.on('end', handleEnd);
});
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question