简体   繁体   中英

Async function inside MQTT message event

I'm using MQTTjs module in a Node app to subscribe to an MQTT broker. I want, upon receiving new messages, to store them in MongoDB with async functions. My code is something as:

client.on('message', (topic, payload, packet) => {

      (async () => {
        await msgMQTT.handleMQTT_messages(topic, payload, process.env.STORAGE,
          MongoDBClient)
      })

    })

But I can't understand why it does not work, ie it executes the async function but any MongoDB query returns without being executed. Apparently no error is issued.
What am I missing?

I modified the code in:

client.on('message', (topic, payload, packet) => {
        try {
            msgMQTT.handleMQTT_messages(topic, payload, process.env.STORAGE,
                MongoDBClient, db)
        } catch (error) {
            console.error(error)
        }
    })

Where:

exports.handleMQTT_messages = (topic, payload, storageType, mongoClient, db) => {

    const dateFormat = 'YYYY-MMM-dddd HH:mm:ss'


    // topic is in the form 
    // 
    const topics = topic.split('/')

    // locations info are at second position after splitting by /
    const coord = topics[2].split(",")

    // build up station object containing GeoJSON + station name
    //`Station_long${coord[0]}_lat${coord[1]}`
    const stationObj = getStationLocs(coord.toString())
    const msg = JSON.parse(payload)

    // what follows report/portici/
    const current_topic = topics.slice(2).join()
    let data_parsed = null

    // parse only messages having a 'd' property
    if (msg.hasOwnProperty('d')) {
        console.log(`${moment().format(dateFormat)} - ${stationObj.name} (topic:${current_topic})\n `)
        data_parsed = parseMessages(msg)

        // date rounded down to the nearest hour
        // https://stackoverflow.com/questions/17691202/round-up-round-down-a-momentjs-moment-to-nearest-minute
        dateISO_String = moment(data_parsed.t).startOf('hour').toISOString();

        // remove AQ from station name using regex
        let station_number = stationObj.name.match(/[^AQ]/).join('')
        let data_to_save = {
            id: set_custom_id(stationObj.name, dateISO_String),
            //`${station_number}${moment(dateISO_String).format('YMDH')}`,
            date: dateISO_String,
            station: stationObj,
            samples: [data_parsed]
        }
        switch (storageType) {
            case 'lowdb':
                update_insertData(db, data_to_save, coll_name)

                break;

            case 'mongodb': // MongoDB Replicaset
                (async () => {
                    updateIoTBucket(data_to_save, mongoClient, db_name, coll_name)
                })()
                break;


            default: //ndjson format
                (async () => {
                    await fsp.appendFile(process.env.PATH_FILE_NDJSON,
                        JSON.stringify(data_to_save) + '\n')
                })()
                //saveToFile(JSON.stringify(data_to_save), process.env.PATH_FILE_NDJSON)
                break;
        }

        // show raw messages (not parsed)
        const show_raw = true
        const enable_console_log = true
        if (msg && enable_console_log) {
            if (show_raw) {
                console.log('----------RAW data--------------')
                console.log(JSON.stringify(msg, null, 2))
                console.log('--------------------------------')
            }
            if (show_raw && data_parsed) {
                console.log('----------PARSED data-----------')
                console.log(JSON.stringify(data_parsed, null, 2))
                console.log('--------------------------------')
            }

        }
    }

}

Only updateIoTBucket(data_to_save, mongoClient, db_name, coll_name) is executed asynchrounsly using mgongodb driver.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM