【发布时间】:2016-06-17 05:51:08
【问题描述】:
我在项目的最后一部分,我正在尝试将来自 json 的数据插入到我的 MySQL 数据库中,这是我的示例数据
{"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 循环?
【问题讨论】:
-
您不能“暂停”
for循环以等待异步操作。for循环是同步的。相反,您将不得不手动迭代,将迭代放入函数中,并仅在异步操作完成时手动开始下一次迭代。 -
@jfriend00 你能给我举个例子吗?这是我在 nodejs (javascript) 中的第一个月
标签: mysql node.js asynchronous callback promise