目前,我正在一个项目上,在使用嵌套查询处理需要更新值的数据时陷入困境。
起初,我没有使用async / await并没有使用“ console.log”调试代码来知道错误在哪里。当我知道它的时候,我意识到javascript不是像瀑布一样的php。我是javascript的初学者,并且是Node js的新手。我花了两个星期学习异步/等待。就是这样,但是我可能对这个概念不完全理解
app.get('/receipts/finalizeSave', (req, res) => {
let sql = "INSERT INTO pembelian SELECT * FROM pembelian_temporary";
let query = pool.query(sql, (err, results) => {
if(err) throw err;
var sqlcheck ="SELECT ID_PRODUK,Qty FROM pembelian_temporary";
var querycheck = pool.query(sqlcheck, async(err, rescheckfirst) =>{
console.log(rescheckfirst,"check"); //biasanya gini buat akses objek
// console.log(rescheckfirst[0].ID_PRODUK);
// console.log(JSON.stringify(rescheckfirst[0].Qty));
if(err) throw err;
for (var z = 0; z < rescheckfirst.length; z++) {
console.log(z,"loop z"); // ini sek dari 0 -> 3
let sqlgetid = "SELECT ON_HAND_PRODUK_GUDANG_OBAT AS STOK FROM obat WHERE ID_PRODUK='"+rescheckfirst[z].ID_PRODUK+"'";//ini gamasalah
let querygetid = await pool.query(sqlgetid, async(err, resget) => {
// if(err) throw err
try{
let stokproduk = await resget[0].STOK;
console.log(z,"loop z check"); //ini langsung 3
// console.log(rescheckfirst.length,"lengh");
// console.log(rescheckfirst[0].ID_PRODUK,"check GetQty");//bisa lek ngene
// console.log(rescheckfirst[1].ID_PRODUK,"check GetQty");//bisa lek ngene
// console.log(rescheckfirst[2].ID_PRODUK,"check GetQty");//bisa lek ngene
let getQty = await rescheckfirst[z].Qty;
// let Qtyproc = parseInt(getQty);
stokproduk=stokproduk+getQty;
let sqlupdstok = "UPDATE obat SET ON_HAND_PRODUK_GUDANG_OBAT='"+mysql.escape(stokproduk)+"' WHERE ID_PRODUK='"+mysql.escape(rescheckfirst[z].ID_PRODUK)+"'";
let queryupdstok = pool.query(sqlupdstok, (err, resupdstok) => {
if(err) throw err
// console.log(rescheckfirst[0].ID_PRODUK);
});
console.log(getQty);
console.log(getQty,"check GetQty");
}catch(err){
// await pool.rollback();
throw err;
}finally{
// res.redirect('/receipts');
let sql1 = "DELETE FROM pembelian_temporary";
let query1 = await pool.query(sql1, (err, results1) =>{
if(err) throw err
res.redirect('/receipts');
});
}
// console.log(Qtyproc);
});
// console.log(rescheckfirst);
// console.log(rescheckfirst[z].Qty);
// console.log(JSON.stringify(rescheckfirst[i].Qty));
}
});
});
});
我的目标是在处理后删除“ pembelian_temporary”中的所有记录之前,在处理后更新“ obat”表上的“ stock”的值或将“ pembelian_temporary”的内容迁移到“ pembelian”。
问题是仅处理单个记录。这是尝试过的数据ive的控制台日志的示例:
上图是控制台日志的输出。我预计z变量的循环将转到1,其中我处理了2个数据。但是,代码只处理单个数据。