0

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.

Aloso
  • 5,123
  • 4
  • 24
  • 41
  • 2
    `return { state: msg, }` runs before the `message` event arrives and triggers `client` to call the function you pass to `on`. – Quentin Jan 23 '23 at 11:24

0 Answers0