简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM