我如何在循环中的JavaScript中在JavaScript中发挥waitfor(延迟)功能



我正在尝试在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是同一脚本中的一个函数,我需要为主机名中的所有元素调用它,同时在每个调用之间保持30秒的间隙。关于如何实现这一目标的任何想法将不胜感激。谢谢!

这是做这种事情的常见模式的简化示例:

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();

您可以使用

之类的东西
let aWait=(x)=>new Promise((resolve)=>setTimeout(resolve,x));

然后将您的循环重写为

之类的东西
 for(let i = 0; i < hostnames.length; i++){
            await checkPageRank(hostnames[i]);
            await aWait(30000);
    }

我以前答案的变体可能包括传递和消耗数组本身,而不是增加计数器:

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);

最新更新