我正在使用jsmodbus(https://github.com/Cloud-Automation/node-modbus)模块在modbus项目中工作,这样我就可以使用readHoldingRegister函数了:
var modbus = require('jsmodbus');
function read(station, callback){
var client = modbus.client.tcp.complete({
'host' : station.ipAdress,
'port' : station.port, //502
'autoReconnect' : true,
'reconnectTimeout' : 1000,
'timeout' : 5000,
'unitId' : 0
});
client.connect();
client.on('connect', function () {
client.readHoldingRegisters(startReg, endReg).then(function (resp) {
return callback(resp);
}).fail(console.log);
});
client.on('error', function (err) {
retrun callback(null);
});
}
我需要为我拥有多少IP而执行此操作并推送每个IP" resp"得到一个数组" allResults"然后返回它,但是当我把上面的代码放在for循环中时,我没有得到结果async.each。
readAll(ip_adresses, (allResults) => {
doSomethingWith(allResults);
});
这样做的正确方法是什么?
答案 0 :(得分:1)
尝试以下
var async = require('async');
...
function read(station, callback) {
...
}
async.map(ips, read, function(err, results) {
if (err)
return console.log(err);
...
// Process results
})
答案 1 :(得分:0)
在承诺中阅读
function read(station) {
return new Promise((resolve, reject) => {
...
client.readHoldingRegisters(startReg, endReg).then(function (resp) {
// here is the point
// in every promise, after resolve, the result will transform to `then` function
// and you will get the result via `read(station).then(result)`
return resolve(resp);
}).fail(console.log)
});
}
function readAll(stations) {
// the stations contain multiple ip, such as [ip1, ip2, ip3...]
// the map function transform every ip to a promise
// use Promise.all to run every promise
// and then, get the results
var readTasks = stations.map(read);
Promise.all(readTask)
.then(allResults => {
doSomethingWith(allResults);
});
}