我是javascript和mqtt的新手。我使用完成的api获取主题,然后将其传递以读取来自该主题的消息。问题是,尽管我确定该主题中只有一条消息,但我每次都会收到越来越多相同的消息,而不是一条消息
我创建了一个仅用于获取ID(主题)的脚本,而创建了第二个没有异步/等待从主题中读取的脚本,我们手动输入该脚本,然后一切正常
const axios = require('axios');
var mqtt = require('mqtt');
const BASE_URL = 'http://localhost:4000';
var client = mqtt.connect("mqtt://test.mosquitto.org")
const params = {
"message": "subscribe"
}
let globalTopic;
// Use some API, for creating topic for mqtt, id is our topic
const configuration = async(params) => {
const response = await axios.post(`${BASE_URL}/mqtt`, params);
console.log(response.data)
const { id } = response.data;
console.log("id", id)
return id;
} //configuration
// connect to mqtt-broker
const subscription = async(topic) => {
console.log("topic", topic)
client.on('connect', function() {
console.log("connected")
client.subscribe(topic, function(err) {
if (err) {
console.log("Can't connect" + err);
process.exit(1);
}
})
})
} // subscription
// try to get messages from topic
const readMessage = async(topic) => {
client.on('message', function(topic, message) {
console.log("message is " + message);
});
}
// call all function
const main = async(params) => {
globalTopic = await configuration(params)
await subscription(globalTopic);
await readMessage(globalTopic);
}
main(params);
configuration(params)
和subscription(globalTopic)
可以正常工作。
readMessage
的 client.on
中执行了多次