I have created the following class in TS:
import MbusMaster, { SerialOptions } from "node-mbus";
{ ... }
export class MbusReader {
private countersToRead: Counter[];
constructor(countersToRead: Counter[]) {
this.countersToRead = countersToRead;
}
readData(connectionOptions: SerialOptions): Counter[] {
const mbusmaster = new MbusMaster(connectionOptions);
const returnValue: Counter[] = [];
mbusmaster.connect();
this.countersToRead.forEach(counter => {
mbusmaster.getData(counter.mbusAddress,(err:string,data:any) => {
const valuedCounter: Counter = { ...counter };
valuedCounter.relevantRecords.forEach((dr,index) => {
const value = data.DataRecord.filter((rec:any) => rec.id === dr.id)[0].Value;
valuedCounter.relevantRecords[index] = { ...valuedCounter.relevantRecords[index], value: value * dr.scaleFactor };
})
returnValue.push(valuedCounter);
console.log(returnValue)
})
})
mbusmaster.close();
return returnValue;
}
}
Now in my index.ts file I use it like this:
const reader = new MbusReader(counters);
const res = reader.readData(options).length;
console.log(res);
Using ts-node I get the following output:
0
[ { mbusAddress: 1, name: 'test', relevantRecords: [ [Object] ] } ]
Why is my code not running in sync? What am I missing?
npm package used: node-mbus