async.parallel停止处理庞大的数组列表

时间:2015-09-09 10:27:50

标签: asynchronous mongoose

我仍然是async模块的新手。基本上,我想使用async.parallel从数组进行批量更新操作,如下所示:

var _ = require('lodash');
var async = require('async');
var list = req.body.dataArr; //the array
var asyncTasks = [];

_.each(hotelList,function(value,key){

    asyncTasks.push(function(callback){ 
            Hotel.find({hotelId:value.hotelId}).exec(function(err,hotels){
                if(err){
                   console.log(err);
                }
                if(hotels.length ==0){
                    //hotel not found
                    console.log('Hotel not found for ID :'+value.hotelId);
                    return;
                }

                hotels[0].countryCode = value.countryCode;
                hotels[0].city        = value.city;

                hotels[0].save(function(err){
                    if(err){
                        console.log('saving failed ... Reason : '+err);
                        return;
                    }
                    console.log('saving successful');
                });

            });
        });

}); 

async.parallelLimit(asyncTasks,function(){
//async.parallelLimit(asyncTasks,10, function(){
    console.log('finish call asyncTask');
    res.json({status:'success'});
});

问题是,当我使用数组中的所有数据(有超过100.000个索引)运行它时,它只停止没有任何消息,因为我等了几分钟,但当我尝试将数组限制为仅使用10 parallelLimit,它只执行10次更新操作:

saving successful

我是如何使用异步的?对不起,如果我的英语不好。

1 个答案:

答案 0 :(得分:0)

您的asyncTasks个函数在完成工作后需要调用callback个参数,以便parallelparallelLimit知道它们何时完成。

_.each(hotelList,function(value,key){

    asyncTasks.push(function(callback){ 
        Hotel.find({hotelId:value.hotelId}).exec(function(err,hotels){
            if(err){
               console.log(err);
               return callback(err);
            }
            if(hotels.length ==0){
                //hotel not found
                console.log('Hotel not found for ID :'+value.hotelId);
                return callback(Error('Not found'));
            }

            hotels[0].countryCode = value.countryCode;
            hotels[0].city        = value.city;

            hotels[0].save(function(err){
                if(err){
                    console.log('saving failed ... Reason : '+err);
                    return callback(err);
                }
                console.log('saving successful');
                callback();
            });
        });
    });
}); 
相关问题