我在我项目的最后一部分,我正在尝试从MySQL数据库中的json插入数据,这是我的示例数据
{"data":
[{"cpos": "g", "cfname": "e", "clname": "ejercito", "cvcount": "4"},
{"cpos": "g", "cfname": "j", "clname": "ejercito", "cvcount": "5"}]}
而且我的函数正在解析样本数据(抱歉,长函数)
checkPositionCandidateInsertVote: function(ref, prid, json, callback){
var len = json.data.length;
for (var i = 0; i < len; i++) {
var fn = (json.data[i].cfname).toLowerCase();
var ln = (json.data[i].clname).toLowerCase();
var c = json.data[i].cvcount;
console.log(fn, ' ', c);
switch((json.data[i].cpos).toLowerCase()){
case "g":
module.exports.getCandiName(fn, ln, "Governor", function(dataa){
//dataa.id
module.exports.insertVotes(prid, ref, c, dataa.id, function(res){
});
});
break;
case "vg":
module.exports.getCandiName(fn, ln, "Vice Governor", function(dataa){
//dataa.id
module.exports.insertVotes(prid, ref, c, dataa.id, function(res){
});
});
break;
case "m":
module.exports.getCandiName(fn, ln, "Mayor", function(dataa){
//dataa.id
module.exports.insertVotes(prid, ref, c, dataa.id, function(res){
});
});
break;
case "vm":
module.exports.getCandiName(fn, ln, "Vice Mayor", function(dataa){
//dataa.id
module.exports.insertVotes(prid, ref, c, dataa.id, function(res){
});
});
break;
case "bm":
module.exports.getCandiName(fn, ln, "Board Member", function(dataa){
//dataa.id
module.exports.insertVotes(prid, ref, c, dataa.id, function(res){
});
});
break;
case "cg":
case "cm":
case "cw":
module.exports.getCandiName(fn, ln, "Congressman", function(dataa){
//dataa.id
module.exports.insertVotes(prid, ref, c, dataa.id, function(res){
});
});
break;
case "c":
module.exports.getCandiName(fn, ln, "Councilor", function(dataa){
//dataa.id
module.exports.insertVotes(prid, ref, c, dataa.id, function(res){
});
});
break;
}
}
}
我的功能正常,但是当我检查数据库时,VoteCount部分中的数据错误。
预期的
e ejercito 4
j ejercito 5
但是在数据库中是
结果
e ejercito 5
j ejercito 5
如果我的查询尚未完成,如何停止我的for循环?
无需停止循环,JS具有异步特性。
事情是,在module.exports.insertVotes(prid, ref, c, dataa.id, function(res){});
执行时间之前,for循环已经完成,因此对于所有情况您最终都会得到las index。
要解决此问题,可以使用forEach
loop。每次迭代都有其自己的范围。
checkPositionCandidateInsertVote: function(ref, prid, json, callback){
json.data.forEach(function(listItem, i){
var fn = (json.data[i].cfname).toLowerCase();
var ln = (json.data[i].clname).toLowerCase();
var c = json.data[i].cvcount;
console.log(fn, ' ', c);
switch((json.data[i].cpos).toLowerCase()){
case "g":
module.exports.getCandiName(fn, ln, "Governor", function(dataa){
//dataa.id
module.exports.insertVotes(prid, ref, c, dataa.id, function(res){
});
});
break;
...
...
...
case "c":
module.exports.getCandiName(fn, ln, "Councilor", function(dataa){
//dataa.id
module.exports.insertVotes(prid, ref, c, dataa.id, function(res){
});
});
break;
}
});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句