我正在尝试在Node.js的循环内添加延迟。我有一个数组,需要为数组的每个元素调用一个函数。要注意的是,每个这样的函数调用之间应该有30秒的间隔。这是我尝试过的-
const cprRedshift = async (page) => {
let query = "select links from schema.table", links = [], ranks = []
let data = await redshiftSelect(query)
data.rows.forEach(element => {
links.push(element.links)
})
let hostnames = await getDomainNames(links)
// one way
for(let i = 0; i < hostnames.length; i++){
await setTimeout(async () => await checkPageRank(hostnames[i]), 30000)
}
// another way
let i = 0
while(i < hostnames.length){
await checkPageRank(page, hostnames[i])
setInterval(() => ++i, 30000)
}
}
checkPageRank
是同一脚本中的一个函数,我需要针对hostnames []数组中的所有元素调用它,同时每次调用之间要保持30秒的间隔。关于如何实现这一点的任何想法将不胜感激。谢谢!
答案 0 :(得分:3)
这是做这种事情的通用模式的简化示例:
const hostnames = ["one", "two", "three", "four", "five", "six"];
function go (index = 0) {
// do whatever you need to do for the current index.
console.log(hostnames[index]);
// if we haven't reached the end set a timeout
// to call this function again with the next index.
if (hostnames.length > index + 1) {
setTimeout(() => go(index + 1), 1000);
}
}
// kick it off
go();
答案 1 :(得分:2)
my previous answer的一种变体可以包括传递和使用数组本身,而不是增加一个计数器:
const hostnames = ["one", "two", "three", "four", "five", "six"];
function go ([current, ...remaining]) {
// do whatever you need to do for the current item.
console.log(current);
// if there are items remaining, set a timeout to
// call this function again with the remaining items
if (remaining.length) {
setTimeout(() => go(remaining), 1000);
}
}
// kick it off
go(hostnames);
答案 2 :(得分:1)
您可以使用
之类的东西let aWait=(x)=>new Promise((resolve)=>setTimeout(resolve,x));
然后将循环重写为
for(let i = 0; i < hostnames.length; i++){
await checkPageRank(hostnames[i]);
await aWait(30000);
}