我正在使用expressJs來路由某些POST請求。 從客戶端傳遞對象的對象,並在服務器中使用for循環遍歷每個對象。陣列中的NodeJs項變量只取得for循環中的第一個值
我的問題,在循環變量cantidad
只需要第一個值,而不是被刷新到pool.query
,但需要正確的價值的pool.query
之前。
所以,下面的行是確定的。
console.log("cantidad before query: " + cantidad);
但是下面的線是壞的。它有第一個價值。
console.log("cantidad in query: " + cantidad);
這是我的代碼的一部分。
for (var key in objects) {
if (objects.hasOwnProperty(key)) {
...
console.log("cantidad before query: " + cantidad);
pool.query(qProducto,idProducto, function (error, results, fields {
if (error) {
...
} else {
console.log("cantidad in query: " + cantidad);
...
這是ExpressJs完整的職位。
app.post("/commanda", function (req, res) {
var idCuenta = req.body.idCuenta;
var idEmpleado = req.body.idEmpleado;
var fechaRegistro = req.body.fechaRegistro;
var cuenta_mesero = "C:" + idCuenta + ":E:" + idEmpleado;
var objects = req.body.objects;
var element = {};
for (var key in objects) {
if (objects.hasOwnProperty(key)) {
var qProducto = "SELECT descripcionProducto FROM PRODUCTO WHERE idProducto = ? ;";
var descProducto = '';
console.log("cantidad in commanda2 : " + objects[key].cantidad);
try {
pool.query(qProducto, objects[key].idProducto, function (error, results, fields) {
if (error) {
console.error(error);
console.error("Failed with query: " + qProducto);
res.status(500).end();
throw error;
} else {
console.log("cantidad in commanda4 : " + objects[key].cantidad);
descProducto = JSON.stringify(results[0].descripcionProducto);
element = {
idProducto:objects[key].idProducto,
cantidad:objects[key].cantidad,
descProducto:descProducto,
cuenta_mesero:cuenta_mesero,
fechaRegistro:fechaRegistro
};
imprimirOrden(element);
}
});
} catch (error) {
callback(error);
}
}
}
printer.printVerticalTab();
res.status(200).end();
});
這是一個物體的外觀。
{ '0':
{ idProducto: '28',
cantidad: '3',
descProducto: 'Product1',
precioProducto: '3500',
precioTotal: 10500,
'$$hashKey': 'object:345' },
'1':
{ idProducto: '29',
cantidad: '2',
descProducto: 'Product2',
precioProducto: '4500',
precioTotal: 9000,
'$$hashKey': 'object:346' } }
好吧,你有一個想法如何實施?使用async.parallel?系列?瀑布? eachSeries?實際上,我的變量'cantidad'不是查詢的結果,而是對象的'object'的一部分。查詢結果是另一個成功更新的變量。 – negrotico19
您是否根據查詢結果更改變量cantidad?如果是,那麼我相信系列功能就是你要找的。它將確保在前一個查詢完成後調用每個查詢。 – itsundefined
閱讀你的編輯評論後,我仍然不明白這個問題。代碼的哪一部分是你改變變量cantidad?因爲您聲明只有第一個值是控制檯記錄的。 – itsundefined