林在我的项目的最后一部分,我试图插入来自JSON数据在我的MySQL数据库这里有我的样本数据遍历异步功能的For循环(DB查询,Node.js的)
{"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;
}
}
}
我的功能/ s工作正常,但是当我检查我的数据库中的数据是错误的VoteCount一部分。
预计
e ejercito 4
j ejercito 5
但在db是
结果
e ejercito 5
j ejercito 5
如何停止我的循环,如果我的查询还没有完成?
您不能“暂停”for循环来等待异步操作。 'for'循环是同步的。相反,您必须手动迭代,将迭代放入函数中,并仅在异步操作完成时手动开始下一次迭代。 – jfriend00
@ jfriend00你能举个例子吗?这是我的第一个月在nodejs(javascript) – something
这里有一些例子:http://stackoverflow.com/questions/29880715/how-to-synchronize-a-sequence-of-promises/29906506#29906506和http:// stackoverflow.com/questions/34191788/how-to-process-a-big-array-applying-a-async-function-for-each-element-in-nodejs/34191957#34191957 – jfriend00