Delay each loop iteration in node js, async

匿名 (未验证) 提交于 2019-12-03 01:23:02

问题:

I have the code below:

var request = require('request'); var cheerio = require ("cheerio"); var async= require("async");  var MyLink="www.mylink.com";      async.series([          function(callback){             request(Mylink, function (error, response, body) {                 if (error) return callback(error);                  var $ = cheerio.load(body);                 //Some calculations where I get NewUrl variable...                 TheUrl=NewUrl;                 callback();             });         },         function(callback){             for (var i = 0; i <=TheUrl.length-1; i++) {                 var url = 'www.myurl.com='+TheUrl[i];                 request(url, function(error, resp, body) {                      if (error) return callback(error);                      var $ = cheerio.load(body);                     //Some calculations again...                     callback();                 });             };         }       ], function(error){         if (error) return next(error);     });

Does anyone have a suggestion about how I can delay each loop iteration in the for loop? Say, the code waits 10 seconds after each iteration is complete. I tried setTimeout but didn't manage that to work.

回答1:

You can set a timeout for the execution of the code at increasing intervals like this:

var interval = 10 * 1000; // 10 seconds;  for (var i = 0; i <=TheUrl.length-1; i++) {     setTimeout( function (i) {         var url = 'www.myurl.com='+TheUrl[i];         request(url, function(error, resp, body) {              if (error) return callback(error);              var $ = cheerio.load(body);             //Some calculations again...             callback();         });     }, interval * i, i); }

So the first one runs right away (interval * 0 is 0), second one runs after ten seconds, etc.

You need to send i as the final parameter in the setTimeout() so that its value is bound to the function argument. Otherwise the attempt to access the array value will be out of bounds and you will get undefined.



回答2:

Another alternative would be to use async.eachSeries. For example:

async.eachSeries(TheUrl, function (eachUrl, done) {     setTimeout(function () {         var url = 'www.myurl.com='+eachUrl;         request(url, function(error, resp, body) {              if (error) return callback(error);              var $ = cheerio.load(body);             //Some calculations again...             done();         });     }, 10000); }, function (err) {     if (!err        
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!