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

237
Views
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 answers
Answer question

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 Report
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!