异步等待不使用两个功能

时间:2020-09-02 00:26:14

标签: javascript node.js

我具有访问数据库以确定每种成分的总排放量的功能。然后将该值保存到一个对象和数据库中。但是,在计算排放总量之前先保存对象。

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();




本质上,next()函数应该在异步函数getEmissionTotal()之后执行

1 个答案:

答案 0 :(得分:2)

library(shiny) library(tidyverse) df_test <- tibble::tribble( ~ Region, ~ Category, "West", "A", "West", "A", "West", "B", "East", "D", "East", "E", "North", "A", "North", "B", "North", "C" ) %>% mutate_all(as.factor) ui <- fluidPage( selectizeInput( "region", "Select region(s):", choices = levels(df_test$Region), multiple = TRUE ), selectizeInput( "category", "Select category/categories:", choices = levels(df_test$Category), multiple = TRUE ), tableOutput("table") ) server <- function(input, output, session) { output$table <- renderTable( df_test %>% filter( # This pattern works, but is not very DRY and there are many # more inputs... if (!is.null(input$region)) Region %in% input$region else TRUE, if (!is.null(input$category)) Category %in% input$category else TRUE ) ) } shinyApp(ui, server) 需要带入getEmissionTotal方法内。另外,您什么也不返回,不等待结果。

emission_total