Nodejs wait between function execution

Viewed 105

I have create a NodeJS App which receive MQTT messages. On message receive I start a function to check in a database and I update data or create data if not exist. I receive 12 messages at the same time, the first message should create the data in database and the others should update the data; but the function is call too fast and the SQL query is slower than my call time and I got multiple data create in my database.

How can I put a delay between my function calls ? Is that possible to make a queue ? Like this :

message 1 arrive -> call my function.
message 2 arrive -> function is busy, wait. Function not busy call function.
message 3 arrive -> function is busy, wait. Function not busy call function.
etc...

It's no easy to explain my issue, I hope you'll understand... Thanks

Sorry for my English...

1 Answers

You should probably be adding the incoming messages to a local queue then you can process them in order.

The other option is to use high QOS subscriptions and control the MQTT acknowledgement messages to the broker, but I don't think MQTT.js supports this.

You should look at using promises to handle the calls to the database as these will very likely be asynchronous so will return before the actions have completed.

Related