node.js - Nodejs 在循环中等待

标签 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()。

我想循环访问组数组一次,并在每个项目之间等待,直到读取末尾

最好的方法是什么?

最佳答案

2017 年更新

使用 es6、promise 和 async/await 现在有一些很好的方法可以做到这一点。例如:

使用异步/等待:

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)

将迭代器协议(protocol)与 setInterval 结合使用

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

关于node.js - Nodejs 在循环中等待,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23316525/

相关文章:

javascript - 从 Angular 端发送文件后,在 Node.js 端编码大文件时出错

javascript - 将函数作为 json 对象中的值访问

node.js - 从同一 Node 应用程序检索 res.json() 数据

node.js - 浏览器客户端无法接收消息

java - 分层死锁(具有依赖性),...或 : how do I get my "wait"s, "notify"s,设计对吗?

java - 如何正确等待用户输入?

java - 应如何处理 CountDownLatch.wait 的 InterruptedException

用于设置核心亲和性的 C++ 风格?

callback - 如何 : Idiomatic Rust for callbacks with gtk (rust-gnome)

cocoa - 自定义 View 应该如何更新模型对象?