Function runs but DB does not update

Greetings. I have a function that works correctly and that does update the DB correctly if it is set up as a separate function connected to a button. However, I need it to be a part of a chain of functions. I set up the chain following this approach:

function1().then(function2).then(function3).then(function4) etc.

each function creates a promise and has a resolve statement inside the allItems.forEach((record) => { statement. All the resolved statements for the promises are in the same location for each function (I tested multiple locations, and this was the one that worked reliably).

When function 3 runs on its own, attached to a button, it runs flawlessly, updating the DB in all the rows it is supposed to update. so the mechanics of the function seem correct.

However, when attached to a chain in the manner mentioned above, this is the ONLY function in the chain that does not complete its DB updates. It does run correctly to the end (per the console.log statements0, but it stops updating the database after the 77th or so record.

I am not sure where the problem might be so I am looking for suggestions on what I could look into or modify in the chaining statement that might help with the ONE function that refuses to consistently update the database.

Thank you.

Hey
I would really recommend you to add code when you ask this kind of questions and not just how the flow of the code is created. It will make it so much easier to actually see the code to find anything that might do this to your loop.

My guesses is the following without seeing any code:

  • The loop does not wait for the DB promise until it continues to the next item. This can be achieved by using async / await.

  • There is so much to do that the web page actually times out after those 77 records.

My suggestion:
Make separate async functions for each of your tasks that you need to execute that will take in the items it need as a parameter. Then call the functions using functionName().then(() => { //next }) or await functionName() to make them all execute in a certain order.

Make the developer console print out timestamps when it starts and when it ends to measure if there is a timeout and if the time form start to end is the same all the time. If it is the same, it’s a timeout.

Most Important of all!
If you have this code in Page Code move it to be backend functions in a backend module. The speed and performance between page code and backend code is not comparable in any way possible.

So any code you ever do that can be executed in backend should be, the rest in page code but always try to move code from frontend to backend when ever it’s possible to do so. It will increase the speed of your calculations, your page speed and make the project more modular and easier to update when pages share functions from backend.

Hope I could spread some light on you.

I think you may be right about your comments. Here’s the code so you can see if there is something unholy in my execution.
all other functions have the same db to work with, so go figure. This is not that complicated a function, I don’t think. I call a function to update the DB because I found that the same code, if placed in the function below, did not work reliably to update the DB. This way, as long as the function runs correctly, it should update all rows of the DB that it is supposed to.

Thank you,

function sumprofitloss(){

//this button caculates the sum of the profit/loss column

return new Promise(resolve => {

$w("#dataset1").onReady( () => {


 console.log("summing profit/loss now");
 let count = $w("#dataset1").getTotalCount(); //get total number of items in DB
  console.log("total count for summing profit/loss now", count);
 var num = count.toString(); 
 //$w("#text77").text = num;
 

///start of loop

wixData.query("DailyBetList")
.limit (1000)
.ascending("_createdDate")
  .find()
  .then( (results) => {

let totalCount = results.totalCount;
let allItems = results.items;

console.log("this is total count for sum of profit loss column  ",totalCount);
//var countResults = 0; //setting these two as global variables to avoid using page interface for data management
//var countWinners = 0;
var sumProfitLoss = 0;
var value1ProfitLoss = 0;
var num5 = " ";
var length1 = 4; //prepare to truncate string
var myString1 = " ";
var myTruncatedString1 = " ";
let valueRowNumber = 0;
allItems.forEach((record) => {

let Id = record._id;
let value = record.hiddenFinalResults;
let valueProfitLoss = record.profitLoss;
let valueRowNumber1 = Number(record.hiddenRowCount);
valueRowNumber = valueRowNumber + 1;
console.log ("this is value row number NEW", valueRowNumber)
/////////////////////////////////////////////////////
//////////////////////////////////////////////////////
//get the value of the item in hidden results column for counting winners and bets predicted as a number
var value2 = Number(value);

//get the value of the profit/loss column
value1ProfitLoss = parseFloat(valueProfitLoss);
console.log ("value1ProfitLoss number first read", value1ProfitLoss);

if (valueRowNumber === 1){

sumProfitLoss = value1ProfitLoss; //make the first profitloss the seed value and place it in the database
//console.log ("sumProfitLoss first read", sumProfitLoss);

num5 = sumProfitLoss.toString(); 
    myString1 = num5; //do silly variable transfer
    myTruncatedString1 = myString1.substring(0,length1); //truncate string
//$w("#text62").text = myTruncatedString1;

///updating database with results
 
 let b_leagueTournament = record.leagueTournament;
 let b_RecommendedBet = record.recommendedBet;
 let b_playerTeamOne = record.playerTeamOne;
 let b_playerTeamTwo = record.playerTeamTwo;
 let b_recommendedBetOdds = record.recommendedBetOdds;
 let b_createdDate = record._createdDate;
 let b_HFR = record.hiddenFinalResults;
 let b_finalResults = record.finalResults;
 let b_profitLoss = record.profitLoss;
 let b_sumProfitLoss = myTruncatedString1; //new value for sumprofitloss column
 let b_rowNumber = record.hiddenRowCount;

let toUpdate = {
 "_id": Id,
 "leagueTournament": b_leagueTournament,
 "recommendedBet": b_RecommendedBet,
 "playerTeamOne": b_playerTeamOne,
 "playerTeamTwo": b_playerTeamTwo,
 "recommendedBetOdds": b_recommendedBetOdds,
 "hiddenFinalResults": b_HFR,
 "_createdDate":b_createdDate,
 "finalResults":b_finalResults,
 "profitLoss":b_profitLoss,
 "sumProfitLoss":b_sumProfitLoss,
 "hiddenRowCount":b_rowNumber
      };

updateBet(toUpdate);


}

if (valueRowNumber > 1 ) {
sumProfitLoss = sumProfitLoss + value1ProfitLoss; ///add the value of the next profitloss calculation and place it in db
console.log("this is sumProfitLoss ", sumProfitLoss, value1ProfitLoss, valueRowNumber);


num5 = sumProfitLoss.toString(); 
length1 = 5; //prepare to truncate string
myString1 = num5; //do silly variable transfer
myTruncatedString1 = myString1.substring(0,length1); //truncate string
//$w("#text62").text = myTruncatedString1;
console.log("this is my truncated string and my row number ", myTruncatedString1 + "  " + valueRowNumber);

/////adding items to db since sum profit loss is now added on each row as it is made

///updating database with results
 //let Id = record._id;
if (valueRowNumber === valueRowNumber1) {

 let b_leagueTournament = record.leagueTournament;
 let b_RecommendedBet = record.recommendedBet;
 let b_playerTeamOne = record.playerTeamOne;
 let b_playerTeamTwo = record.playerTeamTwo;
 let b_recommendedBetOdds = record.recommendedBetOdds;
 let b_createdDate = record._createdDate;
 let b_HFR = record.hiddenFinalResults;
 let b_finalResults = record.finalResults;
 let b_profitLoss = record.profitLoss;
 let b_sumProfitLoss = myTruncatedString1; //new value for sumprofitloss column
 let b_rowNumber = record.hiddenRowCount;

let toUpdate = {
 "_id": Id,
 "leagueTournament": b_leagueTournament,
 "recommendedBet": b_RecommendedBet,
 "playerTeamOne": b_playerTeamOne,
 "playerTeamTwo": b_playerTeamTwo,
 "recommendedBetOdds": b_recommendedBetOdds,
 "hiddenFinalResults": b_HFR,
 "_createdDate":b_createdDate,
 "finalResults":b_finalResults,
 "profitLoss":b_profitLoss,
 "sumProfitLoss":b_sumProfitLoss,
 "hiddenRowCount":b_rowNumber
      };

      updateBetSum(toUpdate);
 
} ///end valuerownumber comparison to valuerownumber1 as experiment
 
 
}//end valuerownumber value check > 1


if (value2 === 1) {
countResults = countResults + 1;
countWinners = countWinners + 1;
//console.log("this is countResultsBottom with 1", countResults);
} 

if (value2 === 0) {
countResults = countResults + 1;
//console.log("this is countResultsBottom with 0", countResults);
}


//this is the value of the total count of items that have rinal results in them
var num3 = countResults.toString(); 
var num15 = countWinners.toString();
var num16 = (((countWinners/num)*100).toString()).substring(0,5) +"%";
//num16 = num16 + "%";
$w("#text60").text = num3; //countResults
$w('#text76').text = num15; //countWinners
$w('#text79').text = num16; //percentage of winners


resolve('resolved');////add return to the statement


 } )//end of all items loop


 .catch( (err) => {
 let errMsg = err.message;
 let errCode = err.code;
  } );


});     //results indicator end 


});//end of dataset on ready function


});//// end of promise

}///end of function

//////////////////////////end of function sumprofitloss step 4///////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////

Here’s the code so you can see if there is something unholy in my execution.all other functions have the same db to work with, so go figure. This is not that complicated a function, I don’t think. I call a function to update the DB because I found that the same code, if placed in the function below, did not work reliably to update the DB. This way, as long as the function runs correctly, it should update all rows of the DB that it is supposed to.
Thank you,

function sumprofitloss(){

//this button caculates the sum of the profit/loss column

return new Promise(resolve => {

$w("#dataset1").onReady( () => {


 console.log("summing profit/loss now");
 let count = $w("#dataset1").getTotalCount(); //get total number of items in DB
  console.log("total count for summing profit/loss now", count);
 var num = count.toString(); 
 //$w("#text77").text = num;
 

///start of loop

wixData.query("DailyBetList")
.limit (1000)
.ascending("_createdDate")
  .find()
  .then( (results) => {

let totalCount = results.totalCount;
let allItems = results.items;

console.log("this is total count for sum of profit loss column  ",totalCount);
//var countResults = 0; //setting these two as global variables to avoid using page interface for data management
//var countWinners = 0;
var sumProfitLoss = 0;
var value1ProfitLoss = 0;
var num5 = " ";
var length1 = 4; //prepare to truncate string
var myString1 = " ";
var myTruncatedString1 = " ";
let valueRowNumber = 0;
allItems.forEach((record) => {

let Id = record._id;
let value = record.hiddenFinalResults;
let valueProfitLoss = record.profitLoss;
let valueRowNumber1 = Number(record.hiddenRowCount);
valueRowNumber = valueRowNumber + 1;
console.log ("this is value row number NEW", valueRowNumber)
/////////////////////////////////////////////////////
//////////////////////////////////////////////////////
//get the value of the item in hidden results column for counting winners and bets predicted as a number
var value2 = Number(value);

//get the value of the profit/loss column
value1ProfitLoss = parseFloat(valueProfitLoss);
console.log ("value1ProfitLoss number first read", value1ProfitLoss);

if (valueRowNumber === 1){

sumProfitLoss = value1ProfitLoss; //make the first profitloss the seed value and place it in the database
//console.log ("sumProfitLoss first read", sumProfitLoss);

num5 = sumProfitLoss.toString(); 
    myString1 = num5; //do silly variable transfer
    myTruncatedString1 = myString1.substring(0,length1); //truncate string
//$w("#text62").text = myTruncatedString1;

///updating database with results
 
 let b_leagueTournament = record.leagueTournament;
 let b_RecommendedBet = record.recommendedBet;
 let b_playerTeamOne = record.playerTeamOne;
 let b_playerTeamTwo = record.playerTeamTwo;
 let b_recommendedBetOdds = record.recommendedBetOdds;
 let b_createdDate = record._createdDate;
 let b_HFR = record.hiddenFinalResults;
 let b_finalResults = record.finalResults;
 let b_profitLoss = record.profitLoss;
 let b_sumProfitLoss = myTruncatedString1; //new value for sumprofitloss column
 let b_rowNumber = record.hiddenRowCount;

let toUpdate = {
 "_id": Id,
 "leagueTournament": b_leagueTournament,
 "recommendedBet": b_RecommendedBet,
 "playerTeamOne": b_playerTeamOne,
 "playerTeamTwo": b_playerTeamTwo,
 "recommendedBetOdds": b_recommendedBetOdds,
 "hiddenFinalResults": b_HFR,
 "_createdDate":b_createdDate,
 "finalResults":b_finalResults,
 "profitLoss":b_profitLoss,
 "sumProfitLoss":b_sumProfitLoss,
 "hiddenRowCount":b_rowNumber
      };

updateBet(toUpdate);


}

if (valueRowNumber > 1 ) {
sumProfitLoss = sumProfitLoss + value1ProfitLoss; ///add the value of the next profitloss calculation and place it in db
console.log("this is sumProfitLoss ", sumProfitLoss, value1ProfitLoss, valueRowNumber);


num5 = sumProfitLoss.toString(); 
length1 = 5; //prepare to truncate string
myString1 = num5; //do silly variable transfer
myTruncatedString1 = myString1.substring(0,length1); //truncate string
//$w("#text62").text = myTruncatedString1;
console.log("this is my truncated string and my row number ", myTruncatedString1 + "  " + valueRowNumber);

/////adding items to db since sum profit loss is now added on each row as it is made

///updating database with results
 //let Id = record._id;
if (valueRowNumber === valueRowNumber1) {

 let b_leagueTournament = record.leagueTournament;
 let b_RecommendedBet = record.recommendedBet;
 let b_playerTeamOne = record.playerTeamOne;
 let b_playerTeamTwo = record.playerTeamTwo;
 let b_recommendedBetOdds = record.recommendedBetOdds;
 let b_createdDate = record._createdDate;
 let b_HFR = record.hiddenFinalResults;
 let b_finalResults = record.finalResults;
 let b_profitLoss = record.profitLoss;
 let b_sumProfitLoss = myTruncatedString1; //new value for sumprofitloss column
 let b_rowNumber = record.hiddenRowCount;

let toUpdate = {
 "_id": Id,
 "leagueTournament": b_leagueTournament,
 "recommendedBet": b_RecommendedBet,
 "playerTeamOne": b_playerTeamOne,
 "playerTeamTwo": b_playerTeamTwo,
 "recommendedBetOdds": b_recommendedBetOdds,
 "hiddenFinalResults": b_HFR,
 "_createdDate":b_createdDate,
 "finalResults":b_finalResults,
 "profitLoss":b_profitLoss,
 "sumProfitLoss":b_sumProfitLoss,
 "hiddenRowCount":b_rowNumber
      };

      updateBetSum(toUpdate);
 
} ///end valuerownumber comparison to valuerownumber1 as experiment
 
 
}//end valuerownumber value check > 1


if (value2 === 1) {
countResults = countResults + 1;
countWinners = countWinners + 1;
//console.log("this is countResultsBottom with 1", countResults);
} 

if (value2 === 0) {
countResults = countResults + 1;
//console.log("this is countResultsBottom with 0", countResults);
}


//this is the value of the total count of items that have rinal results in them
var num3 = countResults.toString(); 
var num15 = countWinners.toString();
var num16 = (((countWinners/num)*100).toString()).substring(0,5) +"%";
//num16 = num16 + "%";
$w("#text60").text = num3; //countResults
$w('#text76').text = num15; //countWinners
$w('#text79').text = num16; //percentage of winners


resolve('resolved');////add return to the statement


 } )//end of all items loop


 .catch( (err) => {
 let errMsg = err.message;
 let errCode = err.code;
  } );


});     //results indicator end 


});//end of dataset on ready function


});//// end of promise

}///end of function

//////////////////////////end of function sumprofitloss step 4///////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////

All functions in this chain run independent of each other, but they need to run in specific order so the DB is correctly modified with the additional change each function performs.