林在我的項目的最後一部分,我試圖插入來自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