等待for循环结束以继续javascript中的函数



我有一个问题!我希望函数getMealSummary((在for循环已经完成之后返回(我没有包括返回键,因为函数很大,我只是在这一部分有点怀疑(。

如何使用async/await或promise来完成此操作?

感谢

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))
} 

您可以将map()Promise.all组合用于以下操作:

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)
}
}

这只是一个简单的版本,给你一个基本的想法。我没有包括您在recipesArray上面声明的所有变量。这些将需要根据需要包括在内。

最新更新