【问题标题】:async.parallel stops working on huge list of arrayasync.parallel 停止处理庞大的数组列表
【发布时间】:2015-12-05 06:40:28
【问题描述】:

我还是异步模块的新手。基本上,我想使用 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

我使用异步的方式有什么问题吗?对不起,如果我的英语不好。

【问题讨论】:

    标签: asynchronous mongoose


    【解决方案1】:

    您的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();
                });
            });
        });
    }); 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-31
      • 1970-01-01
      • 2019-11-01
      • 2023-04-06
      • 2020-06-05
      相关资源
      最近更新 更多