Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

147
Views
Why does my code not run synchronously when I don't use any async methods

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

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!