일부 POST 요청을 라우팅하는 데 expressJs를 사용하고 있습니다. 클라이언트 측에서 객체 객체를 전달하고 서버에서 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의 전체 POST입니다.
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();
});
이렇게 보이는 것은 개체의 모양입니다. 기능 for
동기하지만 기능 poll.query
비동기이기 때문에
{ '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을 사용하고 있습니까? 시리즈? 폭포? 각 시리즈? 사실, 내 변수'cantidad'는 질의의 결과가 아니라 객체'objects'의 일부입니다. 쿼리 결과는 성공적으로 업데이트되는 또 다른 변수입니다. – negrotico19
검색어 결과에 따라 변수 cantidad를 변경 하시겠습니까? 그렇다면 시리즈 기능이 당신이 찾고있는 것이라고 믿습니다. 이전 쿼리가 완료된 후에 각 쿼리를 호출해야합니다. – itsundefined
편집 된 설명을 읽은 후에도 여전히 문제를 이해하지 못합니다. 어떤 코드 부분에서 cantidad 변수를 변경하고 있습니까?왜냐하면 첫 번째 값만 콘솔에 기록된다는 것입니다. – itsundefined