I was trying to use Google Sheets as my inventory manager. Every time I got bulk orders, I run them through a for loop and decrease the corresponding stock from another sheet. So I'm using "setValue" function to write data to Sheets.
The problem here is, I'm reading the current stock in a loop and writing the decreased stock in the same loop. However, "setValue" doesn't seem to work until the loop fully ends.
For example,
Milk = 5
>>New orders arrived with this order (1 milk, 1 bread, 1 coffee, 1 milk)
So here I will have a loop of 4 for each item.
For index 0, I read current stock from stock sheet (5). Then I check new order quantity (1). So setValue(4). For index 1,... For index 2,... For index 3, I read current stock from the same stock sheet. It supposed to be 4, but it reads 5. The data supposed to be written 3 recursions before.
So the end result becomes;
Milk = 4
But it supposed to be
Milk = 3
Hope I was able to tell you the problem. So setValue function runs but it does not affect the corresponding sheet until the loop is over. That's why I cannot use it as a live database. Have you ever encountered a problem like this before?
Code looks like this
for(ordersArray){
for(stocksArray){
read stock from sheets
calculate new stock quantity
write new quantity with setValue //here this suppose to write on each loop but it writes only at the end of the loop
}
}
read stock from sheetspart. Moreover, just like @Cooper has mentioned, you might want to take a look at the Best Practices documentation in Apps Script. - ale13