I am new to Javascript. I am trying to retrieve data from a MQTT broker through an async JavaScript function, querydevice
. Here I am successfully getting a response from functions.logger.log(`Query msg retrived from MQTT ${msg}`)
as expected.
const querydevice = async () => {
let msg;
try {
await client.subscribe("test/result");
client.on('message', function(topic, message) {
msg = message.toString();
var tp = topic.toString();
client.end();
functions.logger.log(
`Query msg retrived from MQTT ${msg}`
);
});
return {
state: msg,
}
} catch (e) {
process.exit();
}
};
I am calling the function querydevice
in another function called app.onQuery
as below. But I am not getting a correct response in functions.logger.log(`Device state:${dt.state}`)
. It shows undefined
in place of the dt.state
variable in the logs.
app.onQuery(async (body) => {
const dt = await querydevice();
functions.logger.log(`Device state:${dt.state}`);
return {
requestId: body.requestId,
payload: {
devices: {
"OOB-Group-7": {
on: false,
online: true
}
}
}
}
});
Can some one guide me where I am doing wrong?
I tried removing await
, used .then
instead in app.onQuery
function. Also I tried .toString()
for the dt
variable.