Node.js - sleep required

Consider the following scenario:

Inside one of my cron jobs, I'm requesting someone else's service that only allows for 3600 seconds. The API is similar GetPersonForName=string. Think that I have several peoplein my database, and I need to update their information when I can, I go through my database for all people and call this API. Example

// 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
        })
    })
})

Not sure if sleep is even ideal, but I need to wait 3600 seconds after every request I make.

+4
source share
1 answer

You can use a setTimeoutrecursive function to do this:

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

All Articles