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?
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()));
});
});
}