我希望以递归方式遍历某些函数,以便在最后一个函数之后再次进入第一个函数并且它将永远存在。任何人都可以帮我解决这个问题吗?我还想知道是否有适当的教程或某些东西可以帮助我解决节点js循环和流控制中的这些问题。我虽然尝试了在线教程,但无法正确理解。
var util = require('util');
var async = require('async');
var SensorTag = require('./index');
var USE_READ = true;
SensorTag.discover(function(sensorTag) {
console.log('discovered: ' + sensorTag);
sensorTag.on('disconnect', function() {
console.log('disconnected!');
process.exit(0);
});
async.series([
/*func 1*/
function(callback) {
console.log('connectAndSetUp');
sensorTag.connectAndSetUp(callback);
},
/*func 2*/
function(callback) {
console.log('readDeviceName');
sensorTag.readDeviceName(function(error, deviceName) {
console.log('\tdevice name = ' + deviceName);
callback();
});
},
/*func 3*/
function(callback) {
console.log('readSystemId');
sensorTag.readSystemId(function(error, systemId) {
console.log('\tsystem id = ' + systemId);
callback();
});
}
})
})
当我执行它时,func 1 - >功能2 - > func 3然后挂起。我需要一次又一次地递归循环。
编辑代码:我试图循环使用某些功能,而不是全部
var util = require('util');
var async = require('async');
var SensorTag = require('./index');
var USE_READ = true;
SensorTag.discover(function(sensorTag) {
console.log('discovered: ' + sensorTag);
sensorTag.on('disconnect', function() {
console.log('disconnected!');
process.exit(0);
});
//function loop(){
async.series([
/*func 1*/
function(callback) {
console.log('connectAndSetUp');
sensorTag.connectAndSetUp(callback);
},
function loop(callback){
/*func 2*/
function(callback) {
console.log('readDeviceName');
sensorTag.readDeviceName(function(error, deviceName) {
console.log('\tdevice name = ' + deviceName);
callback();
});
},
/*func 3*/
function(callback) {
console.log('readSystemId');
sensorTag.readSystemId(function(error, systemId) {
console.log('\tsystem id = ' + systemId);
callback();
});
},
function(callback){
loop()
callback()
}
}
/*
function(callback) {
console.log('readDeviceName');
sensorTag.readDeviceName(function(error, deviceName) {
console.log('\tdevice name = ' + deviceName);
callback();
});
},
function(callback) {
console.log('readSystemId');
sensorTag.readSystemId(function(error, systemId) {
console.log('\tsystem id = ' + systemId);
callback();
});
},*/
/*func 4*/
loop();
]);
}
})
答案 0 :(得分:1)
您可以使用forever function from async,并在此调用中使用async.series
答案 1 :(得分:0)
你可以做到
function loop(){
async.series([
// your func here
/*func 4*/
, function(callback){
loop()
callback()
}
}
修改强>
然后调用它开始
loop();
另一个编辑:
也许根本不需要异步
sensorTag.connectAndSetUp(readDevice);
function readDevice() {
console.log('readDeviceName');
sensorTag.readDeviceName(function(error, deviceName) {
console.log('\tdevice name = ' + deviceName);
readSystemId();
});
}
function readSystemId() {
console.log('readSystemId');
sensorTag.readSystemId(function(error, systemId) {
console.log('\tsystem id = ' + systemId);
readDevice(); // start over again
});
}