Fetch and update records while looping through an array in IONIC3


#1

I am working on a store management project and I got hooked here for some days now. I am trying to add sale items to saleItem table then update quantity left and quantity sold in both product and supplyItem table.

The code below work fine if there is no duplicate product in the itemList i.e if a product is not added more than once but only update the last product if duplicate product is added.

Is there anything I need to know about making asynchronous request to IONIC SQLite?

addSaleItems(saleID, store){
try{
  this.itemList.forEach((item) => {
    let query = "INSERT INTO SaleItem (";
    query += "Name, IsActive, TheSale, TheProduct, BatchNo, UnitPrice, Total, TotalCostPrice, Profit_Loss, Quantity";
    query += ") VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

    let data = [item.TheProductName,'true',saleID,item.TheProduct,item.BatchNo,item.UnitPrice,item.Total,item.TotalCostPrice,item.Profit_Loss,item.Quantity];

    this.database.noRetValQuery(query, data).then((retval) => {
      let prod_q = "SELECT Quantity FROM Product WHERE ID = ?";
      let prod_d = [item.TheProductID]
      this.database.retValQuery(prod_q, prod_d).then((prodRetVal) => {
        let leftPro = Number(prodRetVal[0].Quantity) - Number(item.Quantity);
        let prod_data = [leftPro, item.TheProductID];
        return prod_data;
      })
      .then((prod_data) => {
        let prod_query = "UPDATE Product SET Quantity = ? WHERE ID = ?";
        this.database.noRetValQuery(prod_query, prod_data).then((retval) => { });
      })


      let queryPro = "SELECT QuantitySold, QuantityLeft FROM SupplyItem WHERE BatchNo = ? AND TheProduct = ? AND TheStore = ? LIMIT 1";
      let dataPro = [item.BatchNo, item.TheProductID, store];
      this.database.retValQuery(queryPro, dataPro).then((saleRetVal) => {
        let qtyS = Number(saleRetVal[0].QuantitySold) + Number(item.Quantity);
        let qtyL = Number(saleRetVal[0].QuantityLeft) - Number(item.Quantity);
        let sup_data = [qtyL, qtyS, item.BatchNo, item.TheProductID];
        return sup_data;
      }).then((sup_data) => {
        //Update Supply Items
        let sup_query = "UPDATE SupplyItem SET QuantityLeft = ?, QuantitySold = ? WHERE BatchNo = ? AND TheProduct = ?";
        this.database.noRetValQuery(sup_query, sup_data).then((retval) => { })
      });
    });
  });
} finally {
  this.dismissView();
}
}