Как я могу сделать функцию waitFor (задержка) в JavaScript внутри цикла? - PullRequest
0 голосов
/ 24 мая 2019

Я пытаюсь добавить задержку внутри цикла в 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 секунд между каждым вызовом. Любая идея о том, как этого добиться, будет оценена. Спасибо!

Ответы [ 3 ]

3 голосов
/ 24 мая 2019

Вот упрощенный пример общей схемы выполнения подобных действий:

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();
2 голосов
/ 24 мая 2019

Вариант мой предыдущий ответ может включать передачу и использование самого массива вместо увеличения счетчика:

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);
1 голос
/ 24 мая 2019

Вы можете использовать что-то вроде

let aWait=(x)=>new Promise((resolve)=>setTimeout(resolve,x));

Затем переписать свой цикл на что-то вроде

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