Help with async/await for loop + function call

Hello, I would appreciate some help with an await issue I am having. I am creating a json object containing a meal plan day by day. Everything works great within the calculateMeals function and order within that works fine. However the console log of “full mealplan” executes before the for loop is finished, in fact it executes before it even hits the first log within it. Is there any way to wait for all elements of the loop to finish before that data is used?

I also tried a few different syntax such as using an index ( var i = 0 ; i < days.length; i++)

for (var day in days){
        mealPlan[days[day]] = {}  
        mealPlan = await calculateMeals(mealPlan,goalCalories,day)  
        weekRemainCals = weekRemainCals + remainingCals
    }
console.log("full mealplan",mealPlan)
console.log("Total remaining calories for week",weekRemainCals)  
async function calculateMeals (mealPlan,remainingCals){
	lots of code here
	return(mealPlan)
}

everything I am seeing is that this should work, it does execute them in order of the for loop correctly but it won’t wait for the for loop to finish.

I tried putting this into a single function

await calculateMeals(mealPlan,goalCalories).then( () => {
        console.log("full mealplan",mealPlan)
        console.log("Total remaining calories for week",weekRemainCals)
    }) 

but even this is executing the console logs before the calculateMeals has even started. I have a very hard time wrapping my brain around synchronicity as it just doesn’t make logical sense to me. I understand the why but it seems very difficult to force things to operate in a very specific sequence.

My assumption is that the return within the calculateMeals function is executing and the nested for loops within it are just executing in the correct order by luck. I need absolutely everything to finish before working with the mealPlan object

I ran into this awhile ago to, I found my answer here:

Yeah saw this article awhile back but thanks for reminding me about it. It seems what I am doing should work. using a foreach won’t work so I used a for in or just a counter for loop. I will play with some simple examples from it and fill in my actual case and see if I can get that to work

Figured it out, was missing an await on a query. Now I just have to redo everything because it is much too slow with full data :joy: