Nodejs在循环中等待

时间:2014-04-26 21:08:02

标签: node.js wait idioms

我想在一个循环中等待,实现这个目标的最佳方法是什么?

这是我的实际代码:

var groups = ['461', '6726', '3284', '4', '121', '11', '399', '1735', '17', '19', '1614 ];
groups.forEach(function (value) {
            myfunction(value);
        });

我希望每5分钟调用一次myfunction()。

我想循环遍历groups数组并在每个项目之间等待,直到读完为止

最好的方法是什么?

2 个答案:

答案 0 :(得分:2)

这是使用setTimeout()的简单解决方案:

var groups = ['461', '6726', '3284', '4', '121', '11', '399', '1735', '17', '19', '1614'];
function nextGroup(idx) {
  idx = idx || 0;
  if (idx < groups.length) {
    myfunction(groups[idx]);
    setTimeout(function() {
      nextGroup(idx + 1);
    }, 5 * 60 * 1000);
  }
}
nextGroup();

答案 1 :(得分:1)

2017年更新

使用es6,promises和async / await,现在有一些不错的方法可以做到这一点。例如:

使用async / await:

&#13;
&#13;
const groups = [1, 2, 3, 4, 5];

function wait(milleseconds) {
  return new Promise(resolve => setTimeout(resolve, milleseconds))
}

async function send(groups) {
  for (item of groups) {
    await wait(500)
    console.log(item)
  }
}
send(groups)
&#13;
&#13;
&#13;

使用带有setInterval的迭代器协议

&#13;
&#13;
const groups = [1, 2, 3, 4, 5, 6]

const intv = setInterval(gen => {
  const n = gen.next()
  if (n.done) return clearInterval(intv)

  console.log(n.value)
}, 500, groups[Symbol.iterator]())
&#13;
&#13;
&#13;