Delay each loop iteration in node js, async

后端 未结 4 1026
一个人的身影
一个人的身影 2020-12-14 19:54

I have the code below:

var request = require(\'request\');
var cheerio = require (\"cheerio\");
var async= require(\"async\");

var MyLink=\"www.mylink.com\"         


        
4条回答
  •  余生分开走
    2020-12-14 20:21

    Since you're already using async, async.wilst would do nicely as a replacement for for.

    whilst is an asynchronous while-like function. Each iteration is only run after the previous iteration has called its completion callback. In this case, we can simply postpone execution of the completion callback by 10 seconds with setTimeout.

    var i = 0;
    async.whilst(
        // test to perform next iteration
        function() { return i <= TheUrl.length-1; },
    
        // iterated function
        // call `innerCallback` when the iteration is done
        function(innerCallback) {
            var url = 'www.myurl.com='+TheUrl[i];
            request(url, function(error, resp, body) { 
                if (error) return innerCallback(error); 
                var $ = cheerio.load(body);
                //Some calculations again...
    
                // wait 10 secs to run the next iteration
                setTimeout(function() { i++; innerCallback(); }, 10000);
            });
        },
    
        // when all iterations are done, call `callback`
        callback
    );
    

提交回复
热议问题