Node js Node js - 1 year ago 118
Javascript Question

How to work forEachLimit in node js

What is the working of

forEachLimit
in node js.

async.forEachLimit(array,5,(item,callback)=>{
//something
},(err)=>{
//end of loop
})

Answer Source

It works almost like async.forEach except that it doesn’t run task for all items immediately in parallel. The concurrency value is an integer that tells Async how many tasks are allowed to run simultaneously.Let’s say that our database only allows 5 connections at a time, then we simply change our code to:

app.delete('/messages/:messageIds', function(req, res, next) {
var messageIds = req.params.messageIds.split(',');
//`5` is the `concurrency` argument here
// ----------------------------↴
async.forEachLimit(messageIds, 5, function(messageId, callback) {
    db.delete('messages', messageId, callback);
}, function(err) {
    if (err) return next(err);
    res.json({
        success: true,
        message: messageIds.length+' message(s) was deleted.'
    });
});
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download