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

238
Visualizações
Javascript async/await functions with MQTT subscription

I'm working on getting data from an MQTT broker dynamically for a few different topics. I'm struggling with the asynchronous function that is supposed to get the data.

        async function getData(path){

             client.subscribe(path);

             let data = await client.on('message', function(topic, message){
                 data = JSON.parse(message.toString());
                 console.log(data);
                 return JSON.parse(message.toString())
            })

            console.log(data);
            return data

    }

The console.log outside of the client.on function is shown first in the console and does not display the correct information, the console.log within the client.on function shows the correct data. The getData function gets called later in a useEffect and paired down looks like this

getData(path).then((data)=>{
console.log(data)
}

The data in this console.log is the same incorrect information from before. I have attempted to change the location of the await statements, but that has not fixed it. Do I need to chain an additional promise within the getData function to wait for the message to be recieved?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

It's because client.on function uses callback, not Promise. In your case, your are not waiting for the callback to finish before returning data. You can either use async-mqtt (assuming you are using mqtt at first), or create yourself a Promise :

async function getData(path) {
    client.subscribe(path);

    return new Promise((resolve, reject) => {
        client.on('message', function(topic, message) {
            return resolve(JSON.parse(message.toString()));
        });
    });
}
about 4 years ago · Juan Pablo Isaza Relatório
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