How to add delay in async.js iterator (Node)

I am writing a scanner in Node and just opened the fantastic async.js library . I would not overload the servers that I scan. So I want to introduce a delay between iterations. What is the best way to do this? Can I just call callback () from an iterator inside setTimeout?

+4
source share
2 answers

Since the execution of any async task using the Async library is always signaled by a completion callback, you can simply defer the call by placing it in setTimeout(). Here is an example adapted from an example in async doc:

async.eachSeries(hugeArray, function iterator(item, callback) {
    doSomeIO(item, function(err, result) {
        setTimeout(function() {
            // process err or result here
            callback(err);
        }, 500);
    });
  }
}, function done() {
  //...
});
+3
source

, Async Series :

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) callback();
});
+1

Source: https://habr.com/ru/post/1620017/


All Articles