0
我實際上有一個問題,通過在循環中做很多查詢 它似乎不工作,100%的時間只是查詢數組中的最新數據。Nodejs在一個循環中的多個查詢
CurrentSocket.biznessStatus.ListOfItemsToAdd = ["1", "4"];
if(Object.keys(CurrentSocket.biznessStatus.ListOfItemsToAdd).length >= 1){
for(var id in CurrentSocket.biznessStatus.ListOfItemsToAdd){
var readedIt = CurrentSocket.biznessStatus.ListOfItemsToAdd[id];
pool.getConnection(function(id, err, connection){
if(err) throw err;
console.log("doAction of ListOfItemsToAdd for itemID -> "+readedIt);
connection.query("SELECT COUNT(*) AS it FROM users_biznesspanel WHERE user_id = ? AND ui_id = ?", [CurrentSocket.user_id, readedIt], function(err, result){
if(err) console.log(err);
if(result[0]["it"] != 0){
connection.query("UPDATE users_biznesspanel SET nb = nb + 1 WHERE user_id = ? AND ui_id = ?", [CurrentSocket.user_id, readedIt], function(err, result){
connection.release();
if(err) console.log(err);
console.log("Added item: "+readedIt);
});
}
else{
connection.query("SELECT type FROM items WHERE iid = ?", [readedIt], function(err, result){
if(err) console.log(err);
var catInfo = getItemType(result[0]["type"]);
var insertItem = "INSERT INTO users_biznesspanel(user_id, ui_id, icat, iscat) VALUES(?, ?, ?, ?)";
connection.query(insertItem, [CurrentSocket.user_id, readedIt, catInfo.cat, catInfo.scat], function(err, result){
connection.release();
if(err) console.log(err);
console.log("Inserted item: "+readedIt);
});
});
}
});
}.bind(pool, id));
}
}
您需要重構代碼才能更好地使用控制流。該網站[callbackhell.com](http://callbackhell.com/)有一些關於如何操作的指南。 – Mekicha