Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

150
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda