Sven Brodersen
Sven Brodersen

Reputation: 87

Awaiting for a for loop to end to continue function in javascript

i have one question! I want the function getMealSummary() to return after the for loop has finished already finished (I didnt include the return key because the function is very big and i just had a doubt in this section).

How can I do it with async/await or promises?

Thanks

    export const getMealMicroSummaryHelper = async function getMealSummary(array, populatedFoods, customMeasurements, isRecipe,expertId){
  var [totalZinc, totalCalcium,totalAlphaCarotene,totalBetaCarotene,totalCholine,totalCopper,totalBetaCrypto,totalFluoride,totalVitaminB9,totalIron,
    totalLutein,totalLycopene,totalMagnesium,totalManganese,totalNiacin,totalVitaminB5,totalPhosphorus,totalPotassium,totalRetinol,totalRiboflavin,
    totalSelenium,totalSodium,totalTheobromine,totalVitaminA,totalVitaminB12,totalVitaminB6,totalVitaminC,totalVitaminD,totalVitaminD2,totalVitaminD3,
    totalVitaminE,totalThiamin] = [0, 0, 0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];

  let recipesArray = []

  for(let i = 0; i < populatedFoods.length; i++){
       if(populatedFoods[i].foodType === 4){
            await apiCall("get",`/api/experts/${expertId}/recipes/${populatedFoods[i]._id}`)
          .then(recipe =>{
            recipesArray.push(recipe)
          })
          .catch((err)=>console.log(err))
        } 

Upvotes: 0

Views: 52

Answers (1)

palaѕн
palaѕн

Reputation: 73906

You can use a combination of map() and Promise.all for this like:

async function getMealSummary(array, populatedFoods, customMeasurements, isRecipe, expertId) {
   try {

      let recipesArray = await Promise.all(
         populatedFoods.map(async populatedFoods => {
            if (populatedFoods[i].foodType === 4) {
               let recipe = await apiCall("get", `/api/experts/${expertId}/recipes/${populatedFoods[i]._id}`)
               return recipe;
            }
         })
      )

   } catch (err) {
      console.log(err)
   }
}

This is just a simple version to give you a basic idea. I have not included all the variables that you have declared above recipesArray. Those will need to be included as needed.

Upvotes: 1

Related Questions