Search code examples
node.jsmongodbexpressmonk

For loop not working properly in node js


I want to insert multiple data by for loop , but this code add 2 or 3 data only , then its continue loading loading but nothing happen ...

router.post('/addclient' , function (req , res){  
   var finished = false;
   var user = req.body.username;
   for(var i = 0 ; i <30 ; i++){  
       req.body.username = user + i ;  
       objDB.insert("clientList" ,req.body, function(err, data){
           //if(err) console.log(err);        
           if(i>20){
               finished = true;
           }
        });
    }
    if(finished){
             res.redirect('/client/client-list');      
    }
});

Solution

  • Would be best if you use the async node.js library which provides control flows like running each function in series. You could use the async.whilst() method and restructure your code as:

    router.post('/addclient', function(req, res) {
    
        var user = req.body.username,
            count = 0,
            result = { finished = false };      
    
        async.whilst(
            function () { return count < 30; },
            function (callback) {
                count++;
                req.body.username = user + count.toString();  
                objDB.insert("clientList", req.body, function(err, data){
                    if (err) { return callback(err); }  
                    result["data"] = data;
    
                    if( count > 20 ) result.finished = true;
                    callback(null, result);         
                });     
            },
            function (err, result) {
                if (err) { /* handle err */};
                if (result.finished) res.redirect('/client/client-list');
            }
        );
    });