使用For循环迭代asynchronous函数(db query,Node.js)

我在我的项目的最后一部分,我试图插入数据从JSON在我的MySQL分贝这里是我的样本数据

{"data": [{"cpos": "g", "cfname": "e", "clname": "ejercito", "cvcount": "4"}, {"cpos": "g", "cfname": "j", "clname": "ejercito", "cvcount": "5"}]} 

和示例数据正在parsing我的function(抱歉长function)

 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; } } } 

我的function工作正常,但是当我检查我的分贝数据错误的VoteCount部分。

预期

 e ejercito 4 j ejercito 5 

但在数据库是

结果

 e ejercito 5 j ejercito 5 

如果我的查询尚未完成,如何阻止我的for循环?

没有必要为了循环而停下来,JS有一个asynchronous的美妙之处。

事情是通过module.exports.insertVotes(prid, ref, c, dataa.id, function(res){}); 被执行,for循环已经通过,所以你最终得到所有情况下的las索引。

要解决您可以使用forEach 循环 。 每次迭代都有自己的范围。

  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; } }); }