In this code snippet, my goal is to create a ranking based on the prices and nutrient content of various foods in a Wix database. The process involves calculating an index for each food item:
function calculate() {
var array = [];
wixData.query('Food').find().then(res => {
for (let i = 0; i < res.length; i++) {
const item = res.items[i];
const nutrientOfAmount = item[nutrientId];
let grams = Number(item.grams);
let price = Number(item.price);
var index = (nutrientOfAmount * grams) / price;
array.push(index);
if (Number.isNaN(index)) {
array.pop()
}
}
})
}
$w('#button').onClick(() => calculate());
The issue I am facing is that the if cascade within the for loop is returning multiple foods in the #text but not properly assigning the correct rankings to array[0], array[1], and array[2]. This is because the sorting logic is executing prematurely. I need the sorting to occur only after the for loop has completed processing all the food items.
(Note: Due to additional information required for ranking inside the for loop, I cannot move the if cascade outside. It seems like it may involve utilizing promises for sequential execution.)
I am attempting to execute two sets of code sequentially within a for loop function, ensuring the second part runs only after the first one finishes.