循环之间的节点异步foreachof延迟

时间:2017-05-10 07:27:19

标签: node.js asynchronous foreach

我有一个我正在迭代的对象。现在对于这个对象中的每个键值对,我需要调用一个产生i / o请求的函数,但我需要在这些迭代之间等待。这是函数将迭代,读取第一个对象,将其传递给函数并等待n毫秒,在n毫秒后它将读取第二对,将其传递给函数并再次等待直到列表中的对象结束。我该怎么做?

目前这是我的代码概述

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

1 个答案:

答案 0 :(得分:2)

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.