如何一次调用一个节点循环中的函数

时间:2017-06-08 11:13:19

标签: node.js loops asynchronous settimeout sequential

这个代码块进程首先阻塞,然后阻塞,对于所有请求,我需要一个执行5次迭代的代码停止15秒。然后再从接下来的5次迭代继续,依此类推。

function passotken(token, callback) {


async.waterfall([
function(callback) {
db.executesql("select top 20 ext_id as EMPNUM ,  data as datae from newtable", function (data, err) {

    callback(null, data);
    });
},
function(data, callback) {
    var _json_parse = JSON.parse(JSON.stringify(data));
    var rows = data.length;

    console.log(rows)
    var cnt = 1;

    for (var row = 1; row <= rows; row++) {

    logger.info(_json_parse[row-1].EMPNUM);
    //console.log(dateFormat(_json_parse[row].datae));                      
    var req = 'https://pratik.com/ta/rest/v2/companies/|RHV/employees/|' +_json_parse[row-1].EMPNUM + '/timesheets?date=' + dateFormat(_json_parse[row-1].datae, "isoDate");
    //console.log(req);
    var myXMLText = req;

    reques.push(myXMLText);

    }
   // console.log(reques);

    for (var a = 0; a < rows; a++) {
         //CURRENTLY PROCESSING ALL REQUEST IN IF BLOCK AND STOP FOR 15 SEC FOR ONLY FIRST IF CONDITION AFTER THAT ALL IF CONDITION PROCESSING WITHOUT HALT
    if(a%5==0)
    {
        console.log("if");
        //console.log(reques[a]);

        //postreq(reques[a],token,sleeped(a));
      /*  setTimeout(function(){sleeped(reques[a],token);;

    },15000); */
        sleeped(reques[a],token);


        //SHOULD PROCESS IF BLOCK ONCE AND STOP FOR 15 SEC
    }
    else
    {

        postreqELSE(reques[a],token);
        //SHOULD PROCESS ALL REQUECT IN ELSE BLOCK TILL IF CONDITION ABOVE NOT SATISY

    }

    }

Promise.all(ps)
.then((results) => {
console.log("results"); // Result of all resolve as an array
}).catch(err => console.log("err")); 
},
], function(err, result) {
if (!err)
    console.log("Successfully completed")
else console.log(err);
});
};

function callback() {
console.log("completed successfully");
}

function postreq(request1,token)
{
//BLOCK

    }

    function sleeped(requesarr,token)
    {
    console.log("in sleeping");
    //console.log(requesarr,token)

    setTimeout(function(){
        postreq(requesarr,token);
    },15000);}


    function postreqELSE(request2,token1)
{
console.log("in 3RD function");
   //BLOCK2

    }

1 个答案:

答案 0 :(得分:0)

当然,此问题先前已在此处回答:What is the JavaScript version of sleep()?

以下示例将执行您要求的操作:

var reques = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}
async function checkLoop()
{
  for (var a = 0; a < 20; a++)
  { console.log("["+a+"] a%5 is: "+a%5);
    console.log ( new Date().toLocaleTimeString());
    if(a%5==0)
    { console.log("if");
    console.log ( new Date().toLocaleTimeString());
    await sleep(15000);
    }
    else
    { console.log("else");
    console.log ( new Date().toLocaleTimeString());

    }
  }
}
checkLoop();

这打印出以下内容:(部分)重要的是要注意它将始终在第一次迭代时暂停,因为索引从0开始,而不是1.

[0] a%5 is: 0  
8:58:38 AM  
if  
[1] a%5 is: 1  
8:58:53 AM  
else  
8:58:53 AM  
[2] a%5 is: 2  
8:58:53 AM  
else  
8:58:53 AM  
[3] a%5 is: 3  
8:58:53 AM  
else  
8:58:53 AM  
[4] a%5 is: 4  
8:58:53 AM  
else  
8:58:53 AM  
[5] a%5 is: 0  
8:58:53 AM  
if  
8:58:53 AM  
[6] a%5 is: 1  
8:59:08 AM  
else  
8:59:08 AM  
[7] a%5 is: 2  
8:59:08 AM  
else  
8:59:08 AM  

如果您不能使用异步,请尝试以下方法:(间隔设置为1.5秒,以便于测试。只需将1500更改为15000至= 15秒)

var reques = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20];
var _interval;
var timeToWait = 1500;
function checkLoop(_init)
{
  clearInterval(_interval);
  console.log("checkLoop entered with value of: ", _init);
  var start = (typeof(_init) == "undefined") ? 0 : _init;
  console.log("start is: "+start);
  for (var a = start; a < 20; a++)
  { console.log("["+a+"] a%5 is: "+a%5);
    console.log ( new Date().toLocaleTimeString());
    if(a%5==0)
    { console.log("if");
    console.log ( new Date().toLocaleTimeString());
    (function(_idx){_interval = setInterval(function(){checkLoop(_idx+1)}, timeToWait);})(a)
    break;
    }
    else
    { console.log("else");
    console.log ( new Date().toLocaleTimeString());

    }
  }
}
checkLoop();