[英]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.