I have a function that accesses a database to determine total emissions for each ingredients. This value is then saved into an object and into the database. However, the object is being saved before the emission totals can be calculated.
var emission_total = 0;
      async function getEmissionTotal() {
        for (var x in ingredients) {
          Emission.findOne({food_name:ingredients[x]}).then(result => {
            console.log(result);
            if (result == null) {
              emission_total += 0;
              console.log(emission_total);
            }
            else {
              emission_total += 0.7;
              console.log(emission_total);
            }
          })
          .catch(err => console.log(err));
        }
        return;
      }
      
      async function next() {
        await getEmissionTotal();
      
        const date = req.body.date; 
        const description = req.body.description; 
        const food_list = ingredients;
        const photo = photo_link;
        const nutrients = {
          'calories': req.body.calories,
          'fat': req.body.fat,
          'sugar': req.body.sugar,
          'carbs': req.body.carbs,
          'cholesterol': req.body.cholesterol,
          'protein': req.body.protein,
          'emissions': emission_total
        }
        
        console.log(nutrients);
          
        const newNutrition = new Nutrition({
          date,
          description,
          photo,
          nutrients,
          food_list
        });
        console.log(newNutrition)
        newNutrition.save()
          .then(() => res.json('Nutrition added!'))
          .catch(err => res.status(400).json('Error: ' + err));
     
      }
      next();
In essence, the next() function should be executed after the async function getEmissionTotal()

getEmissionTotal()doesn't return anything to wait foremission_totaldeclaration into thegetEmissionTotal()and thenreturn emission_total. In thenext()function, declare another variableconst emissionTotal = await getEmissionTotal()