[英]How call a function sequentially in a for loop with setInterval
我想按顺序在for循环中执行功能。
我使用node.js,我的代码是...
var insertData = [];
var interval = 500;
function working1(nodeID, keyword, cb){
insertData.push(nodeID);
console.log('working: '+nodeID);
// get data and add value to insertData
}
function working2()
{
// insert insertData to database
}
function getDeviceValue(nodeID){
insertData.push(nodeID);
console.log('getDeviceValue : '+nodeID);
async.series([
function(calllback){
working1(nodeID, 'A', function(data, err){
if (err) console.log(err);
else calllback(null, data);
});
},
function(calllback){
working1(nodeID, 'B', function(data, err){
if (err) console.log(err);
else calllback(null, data);
});
},
], function(err, results){
working2();
});
}
setInterval(function() { // This should work periodically.
dbData = [];
for (var i=1; i<=4; i++)
getDeviceValue('0000'+i);
}, interval);
当我执行以上代码时,它的工作方式类似于...
getDeviceValue : 00001
getDeviceValue : 00002
getDeviceValue : 00003
getDeviceValue : 00004
working : 00001
working : 00002
working : 00003
working : 00004
但我想让它像...
getDeviceValue : 00001
working : 00001
getDeviceValue : 00002
working : 00002
getDeviceValue : 00003
working : 00003
getDeviceValue : 00004
working : 00004
当我搜索它时,答案是“使用承诺”。
如何使用?
要么
还有其他办法吗?
无承诺的解决方案,使用简单的javascript。
var i = 1; var interval = 500; var insertData = []; function working(nodeID){ insertData.push(nodeID); console.log('working: '+nodeID); } function getDeviceValue(nodeID){ insertData.push(nodeID); console.log('getDeviceValue : '+nodeID); working(nodeID);// Changed } function asyncLoop(index) { if(index > 4) return; setTimeout(function() { getDeviceValue('0000'+index); index++; asyncLoop(index); }, interval); } asyncLoop(i);
您可以将第一个console.log
放入async.series
如下所示:
function getDeviceValue(nodeID){
insertData.push(nodeID);
async.series([
function(callback) {
console.log('getDeviceValue : '+nodeID);
callback();
},
function(calllback){
working1(nodeID, 'A', function(data, err){
if (err) console.log(err);
else calllback(null, data);
});
},
function(calllback){
working1(nodeID, 'B', function(data, err){
if (err) console.log(err);
else calllback(null, data);
});
},
], function(err, results){
working2();
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.