nodejs循环批量查询手机归属地
1.async.each
//从数据库中取数据
dataProvider.Phone.getPhonesCount().then(function(result){
if(!result){
return res.json({success:false,msg:"数据为空!"});
}
var ps=2000;
var pn=0;
if(result%ps==0){
pn=result/ps;
}else{
pn=parseInt(result/ps)+1;
}
var arr=new Array();
for(var i=1;i<=pn;i++){
arr[i]=i;
}
//按页循环取数据
console.log("开始。。。");
arr.forEach(function (page) {
dataProvider.Phone.getPhones(ps,page).then(function(phones){
async.each(phones,function(phone,cb){
// console.log(phone.phone);
tool.phoneBelong(phone.phone,function(map){
phone.city=map.city;
phone.is_finish=1;
dataProvider.Phone.updatePhoneCity(phone).then(function(result2){
console.log(phone.phone);
cb&&cb();
})
})
},function(err){
if(err){
console.log("操作失败!");
return ;
}
console.log("执行完成!")
})
})
});
})
async.each循环性能较较,开始测试70万数据时,服务就挂了,后来改用下面的方法就可以了。
2.async.queue
var q = async.queue(function(obj, callback) {
console.log('正在执行:'+obj.index);
obj.run(obj.phone,callback);
}, 5);
function add (phone,cb) {
tool.phoneBelong(phone.phone,function(map){
phone.city=map.city;
phone.is_finish=1;
dataProvider.Phone.updatePhoneCity(phone).then(function(result2){
console.log(phone.phone);
cb&&cb();
}).catch(function (e) {
console.log('error ' + i);
console.log(e);
cb();
})
})
}
q.empty=function(){
console.log('last')
}
q.drain = function() {
console.log('over');
// return res.json({success:true,data:JSON.stringify(userJson)});
}
//从数据库中取数据
dataProvider.Phone.getPhonesCount().then(function(result){
if(!result){
return res.json({success:false,msg:"数据为空!"});
}
var ps=2000;
var pn=0;
if(result%ps==0){
pn=result/ps;
}else{
pn=parseInt(result/ps)+1;
}
var arr=new Array();
for(var i=1;i<=pn;i++){
arr[i]=i;
}
//按页循环取数据
console.log("开始。。。");
arr.forEach(function (page) {
dataProvider.Phone.getPhones(ps,page).then(function(phones){
for(var j=0;j<phones.length;j++){
q.push({phone:phones[j],index:j, run:add}, function(err) {
})
}
})
});
})

浙公网安备 33010602011771号