Как получить данные из вложенного обещания - PullRequest
0 голосов
/ 30 июня 2018

У меня есть две модели, определенные в Sequelize, которые связаны с использованием отношения один ко многим, а затем использовали экземпляр 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);
    })
  });
}

Когда я проверяю, обращаются ли к данным во внутреннем вызове обещания, регистратор показывает данные. Но я только получаю информацию из массива внешних обещаний. Как я могу вернуть данные из внутреннего массива обещаний?

1 Ответ

0 голосов
/ 30 июня 2018

Вы не возвращаете внутреннее обещание во внешнем обратном вызове 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 })
  })
}
...