我在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);
})
});
}
当我检查内部的promise调用中是否正在访问数据时,记录器正在显示数据。但是我只从外部promise数组中接收信息。如何从内部promise数组返回数据?
答案 0 :(得分:1)
您不会在外部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 })
})
}