首页 > 解决方案 > 如何从嵌套的 Promise 中接收数据

问题描述

我在 Sequelize 中定义了 2 个使用一对多关系关联的模型,然后使用 Sequelize 实例填充数据库。

Connection  = new Sequelize({...});
Const Recipe = Connection.define('recipe', {name: Sequelize.STRING})
Const Ingredient = Connection.define('ingredient', {name: Sequelize.STRING})
Recipe.hasMany(ingredients);
Ingredient.belongsTo(Recipe);
_.times(3, () => {
   return ProteinRecipe.create({
      name: `SOMENAME`})
  .then((recipe) => {
       _.times(3, () => {
            return recipe.createIngredient({
               name: `INGREDIENT FROM :${recipe.name}`         
  })

我想做的是从所有食谱中检索所有成分数据。

我努力了

const readWithPreferences = (req, res) => {
Recipe.findAll()
  .then((recipes) => {
     return Promise.all(recipes.map((recipe) => {
                  let recipeObj = {};
                  recipeObj.info = recipe.dataValues;
                  recipeObj.ingredients = [];
                  recipe.getIngredients()
                  .then((ingredients)=>{
                    return Promise.all(ingredients.map((ingredient)=>{
                      recipeObj.instructions.push(ingredient.dataValues);
                    }));
                  });
                return recipeObj;
              }))
    .then((recipesArray) => {
        let responseObj = {};
        responseObj.data = recipesArray;
        res.status(200).send(responseObj);
    })
  });
}

当我检查内部承诺调用中是否正在访问数据时,记录器正在显示数据。但我只收到来自外部承诺数组的信息。如何从内部承诺数组返回数据?

标签: javascriptnode.jspromisesequelize.js

解决方案


您没有在外部 Promise.all 回调中返回内部承诺。

const readWithPreferences = (req, res) => {
  Recipe.findAll().then(recipes => {
    return Promise.all(recipes.map(recipe => {
      let recipeObj = { info: recipe.dataValues }
      return recipe.getIngredients()
      .then(ingredients => {
        recipeObj.instructions = ingredients.map(i => i.dataValues)
        // now, return the whole recipe obj:
        return recipeObj
      })
    }))
  })
  .then(data => {
    res.status(200).send({ data })
  })
}

推荐阅读