0

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

schgab
  • 521
  • 5
  • 19
  • Why do you say that you're not using any asynchronous methods when [`mbusmaster.getData`](https://www.npmjs.com/package/node-mbus#getdataaddress-callback) clearly is taking an [asynchronous callback](https://nodejs.org/en/knowledge/errors/what-are-the-error-conventions/)? – Bergi Oct 17 '21 at 14:32
  • @Bergi alright, but how do I tell that it is asynchronous and how do I fix my code? – schgab Oct 17 '21 at 14:38
  • It's only apparent because of following the nodejs conventions for asynchronous callbacks. (I shouldn't have written "clearly"). To tell whether something is asynchronous, normally you should contact the library documentation, but *node-mbus* is lacking :-/. – Bergi Oct 17 '21 at 14:44
  • For how to fix it, see https://stackoverflow.com/questions/18983138/callback-after-all-asynchronous-foreach-callbacks-are-completed and many related questions. Try learning about promises and async/await if you can. – Bergi Oct 17 '21 at 14:46

0 Answers0