gpt4 book ai didi

javascript - 如何使用 setInterval 在 for 循环中顺序调用函数

转载 作者:太空宇宙 更新时间:2023-11-04 01:51:19 25 4
gpt4 key购买 nike

我想顺序执行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

当我搜索它时,答案是“使用 Promise”。

我该如何使用它?

还有其他办法吗?

最佳答案

没有 promise 的解决方案,使用简单的 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);

关于javascript - 如何使用 setInterval 在 for 循环中顺序调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49569427/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com