Rishabh Kaushik
Rishabh Kaushik

Reputation: 96

node async foreachof delay between loops

I have an object over which I am iterating. Now for each of key, value pair in this object, I need to call a function which makes a i/o request but I need to wait between these iterations. That is the function would iterate, read the first object, pass it to function and wait for n milliseconds, after n milliseconds it will read second pair, pass it to function and wait again till the objects in the list get over. How do I do this?

Currently this is outline of my code

async.forEachOfSeries(object1, 
    function(value, key, callback) {    
        //send switch status
        if(object1.key1 == some condition){
            sql.query1
        }
        some io request based on query result
        callback();
        want some delay here
    }, 
    function(err) {
        if( err ) {
            handle error
        } 
        else {
            report success
        }
    }
)

Upvotes: 1

Views: 340

Answers (1)

Amit Yadav
Amit Yadav

Reputation: 1039

Try this - 

async.forEachOfSeries(object1, 
    function(value, key, callback) {    
        //send switch status
        if(object1.key1 == some condition){
            sql.query1
        }
        some io request based on query result
        setTimeout(function () {
              callback();
            }, 10000)
    }, 
    function(err) {
        if( err ) {
            handle error
        } 
        else {
            report success
        }
    }
)

Set the timer delay to whatever time you want. Hope this helps.

Upvotes: 2

Related Questions