2013-10-30 108 views
4

考虑以下情形:的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秒。

+1

而不是睡觉,为什么不使用setTimeout-也可能要考虑asyncjs(https://github.com/caolan/异步) - 这真棒 –

+0

我怎么会在每个人的这个循环中使用setTimeout?请举例? – p0lAris

回答

7

您可以使用setTimeout和递归函数来实现这一点:

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) 
}) 
+0

噢,那可行。我只是在隐性功能上有点犹豫,但这很干净。谢谢! – p0lAris