Search code examples
javascriptnode.jsrequestsleepwait

Node.js — Sleep required


Consider the following scenario:

Inside one of my cron jobs, I am requesting somebody else's service that allows request only 3600 seconds. The API is analogous to GetPersonForName=string. Consider that I have a few people in my database and I need to update their information whenever I possibly I can, I scan my database for all the 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 an idea approach here, but I need to wait for 3600 seconds after every request I make.


Solution

  • You can use setTimeout and a recursive function to accomplish 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)
    })