Node.js – 需要睡眠
考虑以下情况:
在我的一个cron作业里,我请求别人的服务,只允许请求3600秒。 该API类似于GetPersonForName=string
。 考虑到我的数据库中有一些people
,我需要尽可能地更新他们的信息,我扫描我的数据库所有的人,并调用这个API。 例
// mongodb-in-use People.find({}, function(error, people){ people.forEach(function(person){ var uri = "http://example.com/GetPersonForName=" + person.name request({ uri : uri }, function(error, response, body){ // do some processing here sleep(3600) // need to sleep after every request }) }) })
不知道睡觉是否是一个想法,但是我需要等待3600秒。
你可以使用setTimeout
和一个recursion函数来完成这个工作:
People.find({}, function(error, people){ var getData = function(index) { var person = people[index] var uri = "http://example.com/GetPersonForName=" + person.name request({ uri : uri }, function(error, response, body){ // do some processing here if (index + 1 < people.length) { setTimeout(function() { getData(index + 1) }, 3600) } }) } getData(0) })